Here is the code snippet I'm working with:
const retrieveUsers = ({
Model, options,
}) => Model.find(options).catch((e) => {
throw e;
});
@ObjectType({ description: "User model" })
@Entity()
export class UserModel extends BaseEntity {
...
}
@ObjectType()
class Error {
constructor(data: {message: string, code: number}) {
this.message = data.message;
this.code = data.code;
}
@Field(() => Int)
code: number;
@Field(() => String)
message: string;
}
@ObjectType()
class Success {
@Field(() => [ UserModel ])
users: [UserModel];
}
const UserResponseType = createUnionType({
name: "UserResponseType",
types: () => [
Success,
Error,
] as const,
});
@Query(() => [ UserResponseType ])
async retrieveAllUsers(): Promise<typeof UserResponseType> {
const errors = await Promise.resolve([
new Error({
code: 501,
message: "test",
}),
]);
const users = await retrieveUsers({
Model: UserModel,
options: {
...
},
}).catch((e) => e);
return {
errors,
success: users,
};
}
I am aiming to be able to query for Errors or Success in a specific way like this:
query retrieveAllUsers {
retrieveAllUsers {
... on Success {
user {
id
email
}
}
... on Error {
code
message
}
}
}
However, I encountered an error stating:
TS2322: Type '{ errors: Error[]; success: any; }' is not assignable to type 'Error | Success'.
Object literal may only specify known properties, and 'errors' does not exist in type 'Error | Success'.
I attempted to follow an example from (https://typegraphql.com/docs/unions.html#docsNav)[this source]. How can I achieve the mentioned above ability to query?