Created
December 31, 2021 10:31
-
-
Save palanisamym14/b3fa09a0180850b3e02d70cbad7daab3 to your computer and use it in GitHub Desktop.
nest object scalar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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