Skip to content

Commit 90c9dde

Browse files
committed
Merge branch 'B42-Training-master'
2 parents 6e09fe8 + e50b67c commit 90c9dde

File tree

2 files changed

+36
-15
lines changed

2 files changed

+36
-15
lines changed

src/__tests__/cache.test.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import wait from 'waait'
33
import { ObjectId } from 'mongodb'
44
import { EJSON } from 'bson'
55

6-
import { createCachingMethods, idToString } from '../cache'
6+
import {
7+
createCachingMethods,
8+
idToString,
9+
isValidObjectIdString
10+
} from '../cache'
711

8-
const hexId = 'aaaa0000bbbb0000cccc0000'
12+
const hexId = '5cf82e14a220a607eb64a7d4'
913

1014
const docs = {
1115
one: {
@@ -265,3 +269,12 @@ describe('createCachingMethods', () => {
265269
}
266270
})
267271
})
272+
273+
describe('isValidObjectIdString', () => {
274+
it('works', () => {
275+
const trickyId = 'toptoptoptop'
276+
expect(ObjectId.isValid(trickyId)).toBe(true)
277+
expect(isValidObjectIdString(trickyId)).toBe(false)
278+
expect(isValidObjectIdString(hexId)).toBe(true)
279+
})
280+
})

src/cache.js

+21-13
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,23 @@ import { EJSON } from 'bson'
55
import { getCollection } from './helpers'
66

77
export const idToString = id => (id instanceof ObjectId ? id.toHexString() : id)
8-
const stringToId = str => {
9-
if (str instanceof ObjectId) {
10-
return str
8+
9+
// https://www.geeksforgeeks.org/how-to-check-if-a-string-is-valid-mongodb-objectid-in-nodejs/
10+
export const isValidObjectIdString = string =>
11+
ObjectId.isValid(string) && String(new ObjectId(string)) === string
12+
13+
export const stringToId = string => {
14+
if (string instanceof ObjectId) {
15+
return string
1116
}
1217

13-
if (ObjectId.isValid(str)) {
14-
return new ObjectId(str)
18+
if (isValidObjectIdString(string)) {
19+
return new ObjectId(string)
1520
}
1621

17-
return str
22+
return string
1823
}
24+
1925
const fieldToDocField = key => (key === 'id' ? '_id' : key)
2026

2127
// https://github.com/graphql/dataloader#batch-function
@@ -110,13 +116,15 @@ export const createCachingMethods = ({ collection, model, cache }) => {
110116
findByFields: async (fields, { ttl } = {}) => {
111117
const cleanedFields = {}
112118

113-
Object.keys(fields).sort().forEach(key => {
114-
if (typeof key !== 'undefined') {
115-
cleanedFields[key] = Array.isArray(fields[key])
116-
? fields[key]
117-
: [fields[key]]
118-
}
119-
})
119+
Object.keys(fields)
120+
.sort()
121+
.forEach(key => {
122+
if (typeof key !== 'undefined') {
123+
cleanedFields[key] = Array.isArray(fields[key])
124+
? fields[key]
125+
: [fields[key]]
126+
}
127+
})
120128

121129
const loaderJSON = JSON.stringify(cleanedFields)
122130

0 commit comments

Comments
 (0)