Solving automatically generated TypeScript MongoDB types for GraphQL results

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?

Answer №1

To facilitate the mapping between your GraphQL types and your models, you can leverage the mappers feature of codegen. Take a look at these resources for more information:

Since each codegen plugin functions independently without interconnectivity, you will need to manually specify the mappings, like so:

config:
  mappers:
     User: UserDbObject

By doing this, the typescript-resolvers plugin will use UserDbObject as needed (whether as a parent value or return value).

If you prefer an automated approach, you can either programmatically utilize codegen (), or create a .js file instead of a .yaml file that generates the config section based on your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

How to fetch a single element from an array in MongoDB

If I have a document like this: { "id":"1", "references":["AD1","AD2","AD3"] } I want to extract the single value ("AD1") from the array. Is there a way to do that with a MongoDB query? I've tried several methods, but they only return the entire arr ...

What is the best way to delete previously entered characters in the "confirm password" field after editing the password

Is there a way to automatically remove characters in the confirm password field if characters are removed from the password field? Currently, when characters are entered into the password field, characters can also be entered into the confirm password fiel ...

Mongoose - Finding the count of users with the "USA" country in their sessions array

My user table includes an array called sessions for each user, with properties such as IP, country, and OS. Here is a snippet of my table structure: const userSchema = new Schema({ name: { type: String, required: true }, session ...

display a dual-column list using ngFor in Angular

I encountered a situation where I needed to display data from an object response in 2 columns. The catch is that the number of items in the data can vary, with odd and even numbers. To illustrate, let's assume I have 5 data items to display using 2 co ...

Tips for configuring Angular 2 to send all requests in the form of application/x-www-form-urlencoded

My experience with Angular 1 has helped me in understanding how to implement a similar solution, but I'm stuck on the final step. Just like before, the backend developer for our application is set up to accept requests with type application/x-www-for ...

Utilizing asynchronous JavaScript imports within exported classes

Currently, I have a package with async/dynamic exports that I import in the following manner: (async function() { const libEd = await import("../../.cache/ed25519wars/index.js"); })(); I plan to re-expose certain functions from libEd within a class str ...

Encountering [Object] error in Angular's ngbTypeahead functionality

Here is the code for my input field in component.html: <input type="text" class="form-control" [(ngModel)]="searchQuery" [ngbTypeahead]="recommends" name="searchQuery" typeaheadOptionField="user ...

Leveraging $lookup across various collections based on specific conditions

In my system, I have three main collections: drivers, users, and dispatchers. A dispatcher can be either a driver or a user, and the structure of my dispatchers collection is as follows: { "_id" : ObjectId("5c9bb56a56f1a43e8aedf3c1"), "dispatcherId" : Obj ...

I rely on the angular-responsive-carousel library for my project, but unfortunately, I am unable to customize the arrow and dots

When it comes to CSS, I utilize ng deep style in Angular 10 to make changes for browser CSS. However, I am facing an issue where the problem is not being resolved by my CSS code. Here is a snippet of my code: > ::ngdeep .carousel-arrow { > b ...

Exploring the JSON structure within MongoDB

I am looking to build a Json tree using data from 3 collections retrieved from MongoDB. For instance: https://i.sstatic.net/aVdYj.png Each area can have connections to other areas, spaces can be connected to areas and other spaces, and dashes are linked ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

Unexpected token { in Fuse-Box when using Typescript

Here's the beginning of my fuse.ts file import { CSSPluginOptions } from 'fuse-box/plugins/stylesheet/CSSplugin'; import { argv } from 'yargs'; import * as path from 'path'; import { CSSPlugin, CSSResourcePlugin, Env ...

Navigating Apollo queries in a Next.js application with proper authorization

I am currently working on a Progressive Web App built with Next.js that needs to retrieve data from a Wordpress website, and I am still quite new to these technologies. These are the Wordpress plugins that I have installed: WPGraphQL WPGraphQL CORS WPGra ...

What is the best way to export a MongoDB query result as a CSV file while

I am currently dealing with a collection that contains over 5 million records. The task at hand is to query this data and send it to the client as a CSV file. Initially, when the number of records was low, we simply looped through them, wrote them into a f ...

Having trouble establishing a connection between my Node.js application and MongoDB running within a Docker Swarm

I've been working on deploying a nodejs app in docker swarm, but I'm having trouble getting it to connect to the mongodb service. Below is my docker-compose file: version: '3' services: moitrack-teltonika-parser: build: . imag ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Definitions for nested directories within a main index.d.ts

We have developed custom typings for the latest version of material-ui@next and successfully included them in the library during the last beta release. For those interested, you can access the index.d.ts file here. However, there seems to be a problem wi ...

how can I display the JSON description based on the corresponding ID using Ionic 3

I have a JSON file containing: [{ "id": "1", "title": "Abba Father (1)", "description": "Abba Abba Father." }, { "id": "2", "title": "Abba Father, Let me be (2)", "description": "Abba Father, Let me be (2) we are the clay." }, { ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...