Skip to content

Commit

Permalink
feat: expose error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
AuHau committed Dec 3, 2019
1 parent 14b243b commit 05d952f
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 66 deletions.
18 changes: 12 additions & 6 deletions __tests__/api-bzz-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,22 @@ describe('api-bzz-base', () => {
expect(error.status).toBe(404)
})

it('exports resOrError() utility function', () => {
it('exports resOrError() utility function', async () => {
const resOK = { ok: true }
expect(resOrError(resOK)).toBe(resOK)
expect(await resOrError(resOK)).toBe(resOK)

try {
resOrError({
await resOrError({
ok: false,
status: 400,
text: (): Promise<string> =>
Promise.resolve('Message: Some error message'),
statusText: 'Bad request',
})
} catch (error) {
expect(error instanceof HTTPError).toBe(true)
expect(error.status).toBe(400)
expect(error.message).toBe('Bad request')
expect(error.message).toBe('Some error message')
}
})

Expand All @@ -84,12 +86,14 @@ describe('api-bzz-base', () => {
await resJSON({
ok: false,
status: 400,
text: (): Promise<string> =>
Promise.resolve('Message: Some error message'),
statusText: 'Bad request',
})
} catch (error) {
expect(error instanceof HTTPError).toBe(true)
expect(error.status).toBe(400)
expect(error.message).toBe('Bad request')
expect(error.message).toBe('Some error message')
}
})

Expand All @@ -104,12 +108,14 @@ describe('api-bzz-base', () => {
await resText({
ok: false,
status: 400,
text: (): Promise<string> =>
Promise.resolve('Message: Some error message'),
statusText: 'Bad request',
})
} catch (error) {
expect(error instanceof HTTPError).toBe(true)
expect(error.status).toBe(400)
expect(error.message).toBe('Bad request')
expect(error.message).toBe('Some error message')
}
})

Expand Down
34 changes: 20 additions & 14 deletions __tests__/api-bzz-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,16 @@ describe('api-bzz-node', () => {
const manifest = await bzz.list(dirHash)
const entries = Object.values(manifest.entries || {})
const downloaded = await downloadRawEntries(entries)
const downloadedDir = entries.reduce((acc, entry, i) => {
acc[entry.path] = {
data: downloaded[i],
contentType: entry.contentType,
}
return acc
}, {} as Record<string, DirectoryEntry>)
const downloadedDir = entries.reduce(
(acc, entry, i) => {
acc[entry.path] = {
data: downloaded[i],
contentType: entry.contentType,
}
return acc
},
{} as Record<string, DirectoryEntry>,
)
expect(downloadedDir).toEqual(dir)
})

Expand All @@ -198,13 +201,16 @@ describe('api-bzz-node', () => {
const manifest = await bzz.list(dirHash)
const entries = Object.values(manifest.entries || {})
const downloaded = await downloadRawEntries(entries)
const downloadedDir = entries.reduce((acc, entry, i) => {
acc[entry.path] = {
data: downloaded[i],
contentType: entry.contentType,
}
return acc
}, {} as Record<string, DirectoryEntry>)
const downloadedDir = entries.reduce(
(acc, entry, i) => {
acc[entry.path] = {
data: downloaded[i],
contentType: entry.contentType,
}
return acc
},
{} as Record<string, DirectoryEntry>,
)
expect(downloadedDir).toEqual({ ...dir, '/': dir[defaultPath] })
})

Expand Down
4 changes: 2 additions & 2 deletions __tests__/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ describe('browser', () => {
try {
await client.bzz.download('abcdef123456')
} catch (err) {
return err.message
return err.status
}
})
expect(errMessage).toBe('Not Found')
expect(errMessage).toBe(404)
})

it('uploads/downloads the file using bzz', async () => {
Expand Down
26 changes: 16 additions & 10 deletions packages/api-bzz-base/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,28 +68,34 @@ export class HTTPError extends Error {
}
}

export function resOrError<R extends BaseResponse>(res: R): R {
export async function resOrError<R extends BaseResponse>(res: R): Promise<R> {
if (res.ok) {
return res
}

throw new HTTPError(res.status, res.statusText)
const messageMatches = /Message: (.*)$/m.exec(await res.text())
if (messageMatches && messageMatches.length === 2) {
throw new HTTPError(res.status, messageMatches[1])
} else {
throw new HTTPError(res.status, res.statusText)
}
}

export async function resJSON<R extends BaseResponse, T = any>(
res: R,
): Promise<T> {
return await resOrError(res).json<T>()
return (await resOrError(res)).json<T>()
}

export function resStream<R extends BaseResponse<stream.Readable>, T = any>(
res: R,
): stream.Readable | ReadableStream {
return resOrError(res).body
export async function resStream<
R extends BaseResponse<stream.Readable>,
T = any
>(res: R): Promise<stream.Readable | ReadableStream> {
return (await resOrError(res)).body
}

export async function resText<R extends BaseResponse>(res: R): Promise<string> {
return await resOrError(res).text()
return (await resOrError(res)).text()
}

export async function resHex<R extends BaseResponse>(
Expand All @@ -101,7 +107,7 @@ export async function resHex<R extends BaseResponse>(
export async function resSwarmHash<R extends BaseResponse>(
res: R,
): Promise<string> {
const value = await resOrError(res).arrayBuffer()
const value = await resOrError(res).then(res => res.arrayBuffer())
return Buffer.from(new Uint8Array(value)).toString('hex')
}

Expand Down Expand Up @@ -330,7 +336,7 @@ export class BaseBzz<
): Promise<Readable> {
const url = this.getDownloadURL(hash, options)
const res = await this.fetchTimeout(url, options)
return this.normalizeStream(resStream(res))
return this.normalizeStream(await resStream(res))
}

protected async downloadTar(
Expand Down
4 changes: 2 additions & 2 deletions packages/api-bzz-base/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export declare class HTTPError extends Error {
status: number;
constructor(status: number, message: string);
}
export declare function resOrError<R extends BaseResponse>(res: R): R;
export declare function resOrError<R extends BaseResponse>(res: R): Promise<R>;
export declare function resJSON<R extends BaseResponse, T = any>(res: R): Promise<T>;
export declare function resStream<R extends BaseResponse<stream.Readable>, T = any>(res: R): stream.Readable | ReadableStream;
export declare function resStream<R extends BaseResponse<stream.Readable>, T = any>(res: R): Promise<stream.Readable | ReadableStream>;
export declare function resText<R extends BaseResponse>(res: R): Promise<string>;
export declare function resHex<R extends BaseResponse>(res: R): Promise<hexValue>;
export declare function resSwarmHash<R extends BaseResponse>(res: R): Promise<string>;
Expand Down
55 changes: 29 additions & 26 deletions packages/rpc-handler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,35 +74,38 @@ export function normalizeMethods(
): NormalizedMethods {
const v = new Validator(validatorOptions)

return Object.keys(methods).reduce((acc, name) => {
const method = methods[name]
if (typeof method === 'function') {
acc[name] = method
} else if (typeof method.handler === 'function') {
if (method.params == null) {
acc[name] = method.handler
} else {
const check = v.compile(method.params)
acc[name] = function validatedMethod<C = any, P = Record<string, any>>(
ctx: C,
params: P,
) {
// eslint-disable-next-line @typescript-eslint/ban-types
const checked = check(params as Object)
if (checked === true) {
return method.handler(ctx, params)
} else {
throw createInvalidParams(checked)
return Object.keys(methods).reduce(
(acc, name) => {
const method = methods[name]
if (typeof method === 'function') {
acc[name] = method
} else if (typeof method.handler === 'function') {
if (method.params == null) {
acc[name] = method.handler
} else {
const check = v.compile(method.params)
acc[name] = function validatedMethod<
C = any,
P = Record<string, any>
>(ctx: C, params: P) {
// eslint-disable-next-line @typescript-eslint/ban-types
const checked = check(params as Object)
if (checked === true) {
return method.handler(ctx, params)
} else {
throw createInvalidParams(checked)
}
}
}
} else {
throw new Error(
`Unexpected definition for method "${name}": method should be a function or an object with "params" Object and "handler" function.`,
)
}
} else {
throw new Error(
`Unexpected definition for method "${name}": method should be a function or an object with "params" Object and "handler" function.`,
)
}
return acc
}, {} as NormalizedMethods)
return acc
},
{} as NormalizedMethods,
)
}

function defaultOnHandlerError<C = any, P = any>(
Expand Down
6 changes: 3 additions & 3 deletions packages/swarm-browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ export interface SwarmConfig extends ClientConfig {
rpc?: StreamRPC
}

const instantiateAPI = createInstantiateAPI(
createRPC as (endpoint: string) => StreamRPC,
)
const instantiateAPI = createInstantiateAPI(createRPC as (
endpoint: string,
) => StreamRPC)

export class SwarmClient extends BaseClient {
protected bzzInstance: Bzz | void = undefined
Expand Down
6 changes: 3 additions & 3 deletions packages/swarm-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export { Pss } from '@erebos/api-pss'
export { Hex, createHex, hexInput, hexValue } from '@erebos/hex'
export { createRPC } from '@erebos/rpc-node'

const instantiateAPI = createInstantiateAPI(
createRPC as (endpoint: string) => StreamRPC,
)
const instantiateAPI = createInstantiateAPI(createRPC as (
endpoint: string,
) => StreamRPC)

export interface SwarmConfig extends ClientConfig {
bzz?: BzzConfig | Bzz
Expand Down

0 comments on commit 05d952f

Please sign in to comment.