Verify that the GraphQL identifier matches a valid Mongo ObjectId

Currently, I am using Apollo Server to construct a graphql based server that communicates with a MongoDB instance. My goal is to ensure that if the client provides a value for a field that has a graphql type of ID, the value must be a valid mongo ObjectId. Even though mongoose has a utility function to check this, my main concern is to receive a validation error at the graphql level (i.e., a 400) if the value is not a valid ObjectId. I want to avoid encountering a 500 error later in the process when attempting to use that value as an ObjectId and I do not wish to validate the value multiple times within the server.

In essence, I aim to implement validation logic at the graphql level specifically for the ID scalar type, if that clarifies things.

Answer №1

To achieve the desired functionality, it is recommended to implement a custom scalar instead of using the ID type. You have the option to create your own custom scalar or utilize an existing one.

import { Kind, GraphQLError, GraphQLScalarType, ValueNode } from 'graphql';

const MONGODB_OBJECTID_REGEX = /*#__PURE__*/ new RegExp(/^[A-Fa-f0-9]{24}$/);

export const GraphQLObjectID = /*#__PURE__*/ new GraphQLScalarType({
  name: 'ObjectID',

  description:
    'A field whose value adheres to the standard MongoDB Object ID format as specified in the documentation here: https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectId. Example: 5e5677d71bdc2ae76344968c',

  serialize(value: string) {
    if (!MONGODB_OBJECTID_REGEX.test(value)) {
      throw new TypeError(
        `Value is not a valid MongoDB Object ID in the form: ${value}`,
      );
    }

    return value;
  },

  parseValue(value: string) {
    if (!MONGODB_OBJECTID_REGEX.test(value)) {
      throw new TypeError(
        `Value is not a valid MongoDB Object ID in the form: ${value}`,
      );
    }

    return value;
  },

  parseLiteral(ast: ValueNode) {
    if (ast.kind !== Kind.STRING) {
      throw new GraphQLError(
        `Only strings can be validated as MongoDB Object IDs, but received: ${ast.kind}`,
      );
    }

    if (!MONGODB_OBJECTID_REGEX.test(ast.value)) {
      throw new TypeError(
        `Value is not a valid MongoDB Object ID in the form: ${ast.value}`,
      );
    }

    return ast.value;
  },
});

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

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

What could be the reason for AngularJS encoding the URLs for my POST parameters?

Take a look at our service's REST client: self.headers = { Accept: 'application/json', 'Content-Type': 'application/json' }; self.loginClient = $resource(self.baseUrl + '/users/login', { ...

Transferring a data point within the MongoDB aggregation pipeline to be used in sorting the final outcomes

I need help with a MongoDB aggregation I'm working on for tracking game play statistics throughout the week. My goal is to generate a table that displays the percentage of time spent playing each game in a week, organized by games in rows and days of ...

Manage and preserve your node.js/express sessions with this offer

Currently, I am working on a web application that encounters an issue where every time fs.mkdir is called, all the current express sessions are deleted. This causes me to lose all session data and I need a solution to keep these sessions intact. I have att ...

The AJAX function fails to trigger the MVC controller method

I'm attempting to enable inline editing by cell, rather than by row, when double-clicking. Although the initial setup is working, it's not updating the record as expected - the "SaveCustomer" call to the controller isn't triggered. Can anyon ...

The timer freezes at one minute remaining

I encountered a problem with the jQuery countdown I created. Once the count reaches 01:00, it stops instead of continuing to 00:59 with minutes at 0. var start = $('#start'); var countMinutes = 2; var timer; start.on('click', function ...

Node.js Express post query failing to set content type

I have a POST request implemented with the express framework to submit a query to a rest api. Here is the relevant code snippet: var request = require('request'); app.post('/compute', function(req, postResponse) { var queryJSON = re ...

Ways to invoke a function within a React Material-UI component

Currently, I am in the process of setting up a chat system that allows users to add emojis. To achieve this feature, I have devised a function that produces a component containing both text and an image. Here is the function I have implemented: test: fu ...

Issue with Framework7: Swiper slider link not functional

On one of the slides in my swiper slider, there is a link that redirects to a file named year.html Here is the link: <a href="year.html">Add by year, make & model</a> Source code for swiper slider: http://pastebin.com/ggN3TqgA Content ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Is it possible to reuse variables declared in a Javascript function within the same function?

string empCode = ds.Tables[0].Rows[i]["EMP_CODE"].ToString(); string empName = ds.Tables[0].Rows[i]["EMP_NAME"].ToString(); string gradeCode = ds.Tables[0].Rows[i]["GRADE_CODE"].ToString(); tr = new TableRow(); td = new Ta ...

Tips on extracting images from a blob:http localhost URL using jquery, angularjs, or webgl

Can anyone guide me on how to retrieve an image from a localhost URL by using jQuery, AngularJS, or WebGL? I have the URL of the uploaded image file in the format: blob:http%3A//localhost%3A9000/87424398-8ee0-4db1-a653-bc18838d6b24. My goal is to display t ...

No reply from Axios after using async await

Here's a simple method that utilizes Axios to make a call to an API. Interestingly, when the method is called, it doesn't display any output, no logs or error messages. async deActivate(product: Product): Promise<void> { try { ...

Alexa Skills Issue: Problem with Playing AudioPlayer HLS Stream URL

I'm currently using the "AudioPlayer" feature from the "Alexa Skill Kit" to stream an HLS audio format URL. No errors are showing up from AWS Lambda or the Developer Portal. I've been testing it with Silent Echo (). Alexa can play MP3 URLs and so ...

The FuelUx scheduler forgets which day we've chosen when selecting weekly recurrence

When using the fuelUX scheduler, I noticed that after calling the method $('#myscheduler').scheduler("value","JSON VALUE") and selecting a weekly recurrence pattern, the information of the day gets lost. For example, if my input for the recurrenc ...

Restart the _.after function counter

Despite my efforts to search online, I couldn't find a solution for resetting the _.after counter once the code inside has been executed. The goal here is to have the alert box appear only on every 5th click of the button: var cb; cb = _.after(4, fu ...

Retrieving a portion of a file using Jquery ajax

I am struggling with extracting specific content from loaded data using the following simple sample code: $.ajax({ url: 'demo2.htm', success: function(loadeddata){ $("#loaded_data").after(loadeddata); alert('success'); }, ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Finding Exponential Moving Averages (EMA) with the power of JavaScript

Can EMA be calculated using JavaScript? I am attempting to apply the following formula for EMA: EMA = array[i] * K + EMA(previous) * (1 – K) Where K represents the smooth factor: K = 2/(N + 1) And N is the range of values that I want to consider ...