Utilizing the typescript-mongodb
plugin along with graphql-codegen
to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node.
The initial input schema in GraphQL format appears as follows:
type User @entity{
id: ID @id,
firstName: String @column @map(path: "first_name"),
...
Upon generation, the output Typescript types seem accurate:
export type User = {
__typename?: 'User',
id?: Maybe<Scalars['ID']>,
firstName?: Maybe<Scalars['String']>,
...
This corresponds with the DB object structure:
export type UserDbObject = {
_id?: Maybe<String>,
first_name: Maybe<string>,
...
An issue arises when returning the mongo document as a UserDbObject
, as the mapping of fields is not reflected in the output. One possible solution could involve creating a custom resolver to re-map the fields back to the User
type, although this would entail duplicating field mappings across different areas.
For instance, without mapped fields returned by a resolver similar to this:
userById: async(_root: any, args: QueryUserByIdArgs, _context: any) : Promise<UserDbObject> => {
const result = await connectDb().then((db) => {
return db.collection<UserDbObject>('users').findOne({'_id': args.id}).then((doc) => {
return doc;
});
})
...
return result as UserDbObject;
}
Is there a method to leverage the typescript-mongodb
plugin in a way that only entails schema field mapping, followed by automatic resolution using the generated code?