-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (51 loc) · 1.35 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use strict'
const uuid = require('uuid').v4
module.exports = muuid
muuid.parse = parse
muuid.stringify = stringify
muuid.create = create
muuid.isValid = isValid
muuid.ParseError = ParseError
function muuid(MongoDbBinary, opt) {
if (opt !== undefined) return parse(MongoDbBinary, opt)
else return create(MongoDbBinary)
}
function create(MongoDbBinary) {
return new MongoDbBinary(
uuid(null, Buffer.allocUnsafe(16)),
MongoDbBinary.SUBTYPE_UUID
)
}
function parse(MongoDbBinary, string) {
const normalized = normalize(string)
if (normalized === false) throw new ParseError('Invalid hex string')
return new MongoDbBinary(
Buffer.from(normalized, 'hex'),
MongoDbBinary.SUBTYPE_UUID
)
}
function stringify(muuid) {
const buffer = muuid.buffer
return [
buffer.toString('hex', 0, 4),
buffer.toString('hex', 4, 6),
buffer.toString('hex', 6, 8),
buffer.toString('hex', 8, 10),
buffer.toString('hex', 10, 16),
].join('-')
}
function isValid(string) {
return normalize(string) !== false
}
function normalize(string) {
if (typeof string !== 'string') return false
const stripped = string.replace(/-/g, '')
if (stripped.length !== 32 || !stripped.match(/^[a-fA-F0-9]+$/))
return false
return stripped
}
function ParseError(message) {
Error.call(this, message)
this.name = 'ParseError'
}
ParseError.prototype = Object.create(Error.prototype)