Created
April 22, 2020 11:29
-
-
Save sibelius/a8cd4325e29dbd20cfad966a9670a8f1 to your computer and use it in GitHub Desktop.
getObjectId from globalId
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 { fromGlobalId } from 'graphql-relay'; | |
import { Model, Types } from 'mongoose'; | |
// returns an ObjectId given an param of unknown type | |
export const getObjectId = (target: string | Model<any> | Types.ObjectId): Types.ObjectId | null => { | |
if (target instanceof Types.ObjectId) { | |
return new Types.ObjectId(target.toString()); | |
} | |
if (typeof target === 'object') { | |
return target && target._id ? new Types.ObjectId(target._id) : null; | |
} | |
if (Types.ObjectId.isValid(target)) { | |
return new Types.ObjectId(target.toString()); | |
} | |
if (typeof target === 'string') { | |
const result = fromGlobalId(target); | |
if (result.type && result.id && Types.ObjectId.isValid(result.id)) { | |
return new Types.ObjectId(result.id); | |
} | |
if (Types.ObjectId.isValid(target)) { | |
return new Types.ObjectId(target); | |
} | |
return null; | |
} | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment