Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created April 22, 2020 11:29
Show Gist options
  • Save sibelius/a8cd4325e29dbd20cfad966a9670a8f1 to your computer and use it in GitHub Desktop.
Save sibelius/a8cd4325e29dbd20cfad966a9670a8f1 to your computer and use it in GitHub Desktop.
getObjectId from globalId
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