forked from Urigo/graphql-scalars
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(scalars): parse objectid using bson
The `ObjectID` scalar type does some great work ensuring that the data in the database maps to valid ObjectID values for MongoDB. However, in order to use arguments supplied as ObjectID, we still need to convert them to a `bson.ObjectId` type on-the-fly in resolvers or else we'll end up not matching documents that should be matched. This change adds a dependency on the `bson` library so we can use its `ObjectId` class as a means of serializing ObjectID data from the GraphQL API into a usable object for resolvers. Example of code before this change: ```javascript someResolver: (_parent, { id }, { db }) => { const someData = await db.collection('things').findOne({ _id: new ObjectId(id) }) return someData }, ``` And here's what it will look like afterward: ```javascript someResolver: (_parent, { id }, { db }) => { const someData = await db.collection('things').findOne({ _id: id }) return someData }, ``` Similar to `Date` objects which are serialized appopriately in MongoDB if you use `Timestamp`, ObjectIDs should be parsed properly into their correct type before persistence into the database. By doing so, we're ensuring that this type is always consistent. Resolves Urigo#429
- Loading branch information
Showing
6 changed files
with
165 additions
and
21 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,46 +1,45 @@ | ||
import { Kind, GraphQLError, GraphQLScalarType, ValueNode } from 'graphql'; | ||
|
||
const MONGODB_OBJECTID_REGEX = /*#__PURE__*/ /^[A-Fa-f0-9]{24}$/; | ||
import { ObjectId } from 'bson/lib/objectid'; | ||
|
||
export const GraphQLObjectID = /*#__PURE__*/ new GraphQLScalarType({ | ||
name: 'ObjectID', | ||
|
||
description: | ||
'A field whose value conforms with the standard mongodb object ID as described here: https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectId. Example: 5e5677d71bdc2ae76344968c', | ||
|
||
serialize(value: string) { | ||
if (!MONGODB_OBJECTID_REGEX.test(value)) { | ||
serialize(value: ObjectId): string { | ||
if (!ObjectId.isValid(value)) { | ||
throw new TypeError( | ||
`Value is not a valid mongodb object id of form: ${value}`, | ||
); | ||
} | ||
|
||
return value; | ||
return value.toHexString(); | ||
}, | ||
|
||
parseValue(value: string) { | ||
if (!MONGODB_OBJECTID_REGEX.test(value)) { | ||
parseValue(value: string): ObjectId { | ||
if (!ObjectId.isValid(value)) { | ||
throw new TypeError( | ||
`Value is not a valid mongodb object id of form: ${value}`, | ||
); | ||
} | ||
|
||
return value; | ||
return new ObjectId(value); | ||
}, | ||
|
||
parseLiteral(ast: ValueNode) { | ||
parseLiteral(ast: ValueNode): ObjectId { | ||
if (ast.kind !== Kind.STRING) { | ||
throw new GraphQLError( | ||
`Can only validate strings as mongodb object id but got a: ${ast.kind}`, | ||
); | ||
} | ||
|
||
if (!MONGODB_OBJECTID_REGEX.test(ast.value)) { | ||
if (!ObjectId.isValid(ast.value)) { | ||
throw new TypeError( | ||
`Value is not a valid mongodb object id of form: ${ast.value}`, | ||
); | ||
} | ||
|
||
return ast.value; | ||
return new ObjectId(ast.value); | ||
}, | ||
}); |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
/** | ||
* Unfortunately, the file `bson/lib/objectid` does not have its own | ||
* type definitions. This causes TypeScript to throw an error when we | ||
* try and use it instead of the whole bson module. This is mostly | ||
* copy/pasted from the `bson.d.ts` in the installed package. | ||
*/ | ||
declare module 'bson/lib/objectid' { | ||
/** @public */ | ||
export interface ObjectIdLike { | ||
id: string | Buffer; | ||
__id?: string; | ||
toHexString(): string; | ||
} | ||
/** | ||
* A class representation of the BSON ObjectId type. | ||
* @public | ||
*/ | ||
export class ObjectId { | ||
_bsontype: 'ObjectId'; | ||
/* Excluded from this release type: index */ | ||
static cacheHexString: boolean; | ||
/* Excluded from this release type: [kId] */ | ||
/* Excluded from this release type: __id */ | ||
/** | ||
* Create an ObjectId type | ||
* | ||
* @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number. | ||
*/ | ||
constructor(id?: string | Buffer | number | ObjectIdLike | ObjectId); | ||
/* | ||
* The ObjectId bytes | ||
* @readonly | ||
*/ | ||
id: Buffer; | ||
/* | ||
* The generation time of this ObjectId instance | ||
* @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch | ||
*/ | ||
generationTime: number; | ||
/** Returns the ObjectId id as a 24 character hex string representation */ | ||
toHexString(): string; | ||
/* Excluded from this release type: getInc */ | ||
/** | ||
* Generate a 12 byte id buffer used in ObjectId's | ||
* | ||
* @param time - pass in a second based timestamp. | ||
*/ | ||
static generate(time?: number): Buffer; | ||
/* Excluded from this release type: toString */ | ||
/* Excluded from this release type: toJSON */ | ||
/** | ||
* Compares the equality of this ObjectId with `otherID`. | ||
* | ||
* @param otherId - ObjectId instance to compare against. | ||
*/ | ||
equals(otherId: string | ObjectId | ObjectIdLike): boolean; | ||
/** Returns the generation date (accurate up to the second) that this ID was generated. */ | ||
getTimestamp(): Date; | ||
/* Excluded from this release type: createPk */ | ||
/** | ||
* Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. | ||
* | ||
* @param time - an integer number representing a number of seconds. | ||
*/ | ||
static createFromTime(time: number): ObjectId; | ||
/** | ||
* Creates an ObjectId from a hex string representation of an ObjectId. | ||
* | ||
* @param hexString - create a ObjectId from a passed in 24 character hexstring. | ||
*/ | ||
static createFromHexString(hexString: string): ObjectId; | ||
/** | ||
* Checks if a value is a valid bson ObjectId | ||
* | ||
* @param id - ObjectId instance to validate. | ||
*/ | ||
static isValid( | ||
id: number | string | ObjectId | Uint8Array | ObjectIdLike, | ||
): boolean; | ||
|
||
/* Excluded from this release type: toExtendedJSON */ | ||
/* Excluded from this release type: fromExtendedJSON */ | ||
inspect(): string; | ||
} | ||
} |
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
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