Yuki Takei 3 лет назад
Родитель
Сommit
ce257038ea

+ 1 - 0
packages/core/src/index.ts

@@ -7,6 +7,7 @@ export const customTagUtils = _customTagUtils;
 
 // export utils with namespace
 export * as templateChecker from './utils/template-checker';
+export * as objectIdUtils from './utils/objectid-utils';
 export * as pagePathUtils from './utils/page-path-utils';
 export * as pathUtils from './utils/path-utils';
 export * as pageUtils from './utils/page-utils';

+ 27 - 0
packages/core/src/test/util/objectid-utils.test.ts

@@ -0,0 +1,27 @@
+import ObjectId from 'bson-objectid';
+
+import { isValidObjectId } from '../../utils/objectid-utils';
+
+describe('isValidObjectId', () => {
+
+  /* eslint-disable indent */
+  describe.each`
+    arg                                           | expected
+    ${undefined}                                  | ${false}
+    ${null}                                       | ${false}
+    ${'geeks'}                                    | ${false}
+    ${'toptoptoptop'}                             | ${false}
+    ${'geeksfogeeks'}                             | ${false}
+    ${'594ced02ed345b2b049222c5'}                 | ${true}
+    ${new ObjectId('594ced02ed345b2b049222c5')}   | ${true}
+  `('should return $expected', ({ arg, expected }) => {
+    test(`when the argument is '${arg}'`, async() => {
+      // when:
+      const result = isValidObjectId(arg);
+
+      // then:
+      expect(result).toBe(expected);
+    });
+  });
+
+});

+ 21 - 0
packages/core/src/utils/objectid-utils.ts

@@ -0,0 +1,21 @@
+import ObjectId from 'bson-objectid';
+
+import { isServer } from './browser-utils';
+
+// Workaround to avoid https://github.com/williamkapke/bson-objectid/issues/50
+if (isServer()) {
+  global._Buffer = Buffer;
+}
+
+export function isValidObjectId(id: string | ObjectId | null | undefined): boolean {
+  if (id == null) {
+    return false;
+  }
+
+  // implement according to https://www.geeksforgeeks.org/how-to-check-if-a-string-is-valid-mongodb-objectid-in-node-js/
+  if (typeof id === 'string') {
+    return ObjectId.isValid(id) && new ObjectId(id).toHexString() === id;
+  }
+
+  return ObjectId.isValid(id);
+}