Skip to content

Instantly share code, notes, and snippets.

@palanisamym14
Created December 31, 2021 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palanisamym14/b3fa09a0180850b3e02d70cbad7daab3 to your computer and use it in GitHub Desktop.
Save palanisamym14/b3fa09a0180850b3e02d70cbad7daab3 to your computer and use it in GitHub Desktop.
nest object scalar
import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';
import { ObjectId } from 'mongodb';
@Scalar('ObjectId')
export class ObjectIdScalar implements CustomScalar<string, ObjectId> {
description = '`Date`';
parseLiteral(ast): ObjectId {
// check the type of received value
if (ast.kind !== Kind.STRING && ObjectId.isValid(ast.value)) {
return new ObjectId(ast.value); // value from the client input variables
}
throw new Error(`invalid input "${ast.value}"`);
}
serialize(value: unknown): string {
// check the type of received value
if (!(value instanceof ObjectId)) {
throw new Error('ObjectIdScalar can only serialize ObjectId values');
}
return value.toHexString(); // value sent to the client
}
parseValue(value: unknown): ObjectId {
// check the type of received value
if (typeof value === 'string' && ObjectId.isValid(value)) {
return new ObjectId(value); // value from the client input variables
}
throw new Error(`invalid input "${value}"`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment