UNPKG

graphql-objectid-scalar

Version:
56 lines (55 loc) 2.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GraphQLObjectId = exports.isValidMongoDBObjectID = void 0; const graphql_1 = require("graphql"); const language_1 = require("graphql/language"); const error_1 = require("graphql/error"); const mongodb_1 = require("mongodb"); function isValidMongoDBObjectID(id) { /// https://stackoverflow.com/questions/11985228/mongodb-node-check-if-objectid-is-valid id = id + ""; const len = id.length; let valid = false; if (len === 12 || len === 24) { valid = /^[0-9a-fA-F]+$/.test(id); } return valid; } exports.isValidMongoDBObjectID = isValidMongoDBObjectID; exports.GraphQLObjectId = new graphql_1.GraphQLScalarType({ name: "GraphQLObjectId", description: "GraphQLObjectId is a mongodb ObjectId. String of 12 or 24 hex chars", // from database towards client serialize(value) { let result; if (value instanceof mongodb_1.ObjectId) { result = value.toString(); } else if (typeof value === "string" || value instanceof String) { result = value.toString(); } else { throw new error_1.GraphQLError("serialize: value: " + value.toString() + " is not valid ObjectId"); } if (!isValidMongoDBObjectID(result)) { throw new error_1.GraphQLError("serialize: value: " + result + " is not valid ObjectId"); } return result; }, // json from client towards database parseValue(value) { if (!isValidMongoDBObjectID(value)) { throw new error_1.GraphQLError("parseValue: not a valid ObjectId string, require a string with 12 or 24 hex chars, found: " + value); } return new mongodb_1.ObjectId(value); }, // AST from client towards database parseLiteral(ast) { if (ast.kind !== language_1.Kind.STRING) { throw new error_1.GraphQLError("parseLiteral: not a valid ObjectId string, require a string with 12 or 24 hex chars, found: " + ast.kind, [ast]); } const value = ast.value.toString(); return new mongodb_1.ObjectId(value); }, }); exports.default = exports.GraphQLObjectId;