-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
59 lines (53 loc) · 1.5 KB
/
index.ts
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
import mongoose, {
SchemaType,
Document,
Schema,
SchemaOptions,
AnyObject,
} from "mongoose";
import { validate as uuidValidate } from "uuid";
import { Buffer } from "buffer";
class UUIDSchemaType extends Schema.Types.UUID {
static schemaName: "UUID";
static defaultOptions: Record<string, any> = {};
constructor(key: string, options: SchemaOptions<any> = {}) {
super(key, options, "UUID");
}
// Casts UUID String to Buffer
cast(val: string | Buffer): Buffer | Error {
if (typeof val === "string") {
if (uuidValidate(val)) {
return Buffer.from(val, "hex");
}
throw new Error(`Value is not a valid UUID string: ${val}`);
}
if (Buffer.isBuffer(val)) {
return val;
}
throw new Error(`UUID must be a string or buffer, got ${typeof val}`);
}
// Casts for query
castForQuery(val: any): Buffer | Error {
if (typeof val === "string") {
if (uuidValidate(val)) {
return Buffer.from(val, "hex");
}
throw new Error(`Value is not a valid UUID string: ${val}`);
}
if (Buffer.isBuffer(val)) {
return val;
}
throw new Error(`UUID must be a string or buffer, got ${typeof val}`);
}
// Getter to convert Buffer to UUID string
get(fn: Function): any {
return fn(this.toString());
}
// Check if the value is a Buffer
checkRequired(val: Buffer): boolean {
return Buffer.isBuffer(val);
}
}
// Add UUID to Mongoose Schema types
mongoose.Schema.Types.UUID = UUIDSchemaType;
export { UUIDSchemaType };