objectid-utils.ts 604 B

123456789101112131415161718192021
  1. import ObjectId from 'bson-objectid';
  2. import { isServer } from './browser-utils';
  3. // Workaround to avoid https://github.com/williamkapke/bson-objectid/issues/50
  4. if (isServer()) {
  5. global._Buffer = Buffer;
  6. }
  7. export function isValidObjectId(id: string | ObjectId | null | undefined): boolean {
  8. if (id == null) {
  9. return false;
  10. }
  11. // implement according to https://www.geeksforgeeks.org/how-to-check-if-a-string-is-valid-mongodb-objectid-in-node-js/
  12. if (typeof id === 'string') {
  13. return ObjectId.isValid(id) && new ObjectId(id).toHexString() === id;
  14. }
  15. return ObjectId.isValid(id);
  16. }