diff --git a/src/hook-file.ts b/src/hook-file.ts index dd50508..dd84fea 100644 --- a/src/hook-file.ts +++ b/src/hook-file.ts @@ -78,6 +78,7 @@ export class HookFile extends ModuleBuilder { const PageParam = () => this.runtime.type('PageParam'); const QueryError = () => this.runtime.type('QueryError'); const assert = () => this.runtime.fn('assert'); + const isError = () => this.runtime.fn('isError'); const type = (t: string) => this.types.type(t); @@ -156,7 +157,7 @@ export class HookFile extends ModuleBuilder { yield ` const res = await ${guard()}(${serviceName}.${camel( method.name.value, )}(${paramsCallsite}));`; - yield ` if (res.errors.length) {`; + yield ` if (${isError()}(res)) {`; yield ` const handled: ${QueryError()}<${type( 'Error', )}[]> = { kind: 'handled', payload: res.errors };`; @@ -207,7 +208,7 @@ export class HookFile extends ModuleBuilder { })},`; yield ` queryFn: async ({ pageParam }: ${PageParam()}) => {`; yield ` const res = await ${guard()}(${methodExpression}(${paramsCallsite}));`; - yield ` if (res.errors.length) {`; + yield ` if (${isError()}(res)) {`; yield ` const handled: ${QueryError()}<${type( 'Error', )}[]> = { kind: 'handled', payload: res.errors };`; @@ -364,6 +365,7 @@ export class HookFile extends ModuleBuilder { const queryOptions = this.buildQueryOptions(method); const QueryError = () => this.runtime.type('QueryError'); const assert = () => this.runtime.fn('assert'); + const isError = () => this.runtime.fn('isError'); const type = (t: string) => this.types.type(t); const serviceName = camel(`${this.int.name.value}_service`); @@ -392,7 +394,7 @@ export class HookFile extends ModuleBuilder { yield ` const res = await ${guard()}(${serviceName}.${camel( method.name.value, )}(${paramsCallsite}));`; - yield ` if (res.errors.length) {`; + yield ` if (${isError()}(res)) {`; yield ` const handled: ${QueryError()}<${type( 'Error', )}[]> = { kind: 'handled', payload: res.errors };`; diff --git a/src/runtime-file.ts b/src/runtime-file.ts index 0b0a00a..ce90e3a 100644 --- a/src/runtime-file.ts +++ b/src/runtime-file.ts @@ -118,6 +118,14 @@ export class RuntimeFile extends ModuleBuilder { ) as any; return Object.keys(result).length ? result : undefined; - }`; + } + + export function isError(result: { errors: { status?: number | string }[]; data?: any; }): boolean { + return !!result.errors.length && + (Array.isArray(result.data) + ? result.data.length === 0 + : result.data === undefined); + } + `; } }