-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathschema.ts
181 lines (152 loc) · 6.38 KB
/
schema.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import {createHash} from 'crypto'
import {ulid} from 'ulid'
import {Entity, EntityKeys} from "../entity"
import {DataStructure, IdStrategy, SchemaOptions, StopWordOptions} from './options'
import {FieldDefinition, SchemaDefinition} from './definitions'
import {Field} from './field'
import {InvalidSchema} from '../error'
/**
* Defines a schema that determines how an {@link Entity} is mapped
* to Redis data structures. Construct by passing in a schema name,
* a {@link SchemaDefinition}, and optionally {@link SchemaOptions}:
*
* ```typescript
* interface Foo extends Entity {
* aString: string,
* aNumber: number,
* aBoolean: boolean,
* someText: string,
* aPoint: Point,
* aDate: Date,
* someStrings: string[],
* }
*
* const schema = new Schema<Foo>('foo', {
* aString: { type: 'string' },
* aNumber: { type: 'number' },
* aBoolean: { type: 'boolean' },
* someText: { type: 'text' },
* aPoint: { type: 'point' },
* aDate: { type: 'date' },
* someStrings: { type: 'string[]' }
* }, {
* dataStructure: 'HASH'
* })
* ```
*
* A Schema is primarily used by a {@link Repository} which requires a Schema in
* its constructor.
*/
export class Schema<T extends Entity = Record<string, any>> {
readonly #schemaName: string
#fieldsByName = {} as Record<EntityKeys<T>, Field>;
readonly #definition: SchemaDefinition<T>
#options?: SchemaOptions
/**
* Constructs a Schema.
*
* @param schemaName The name of the schema. Prefixes the ID when creating Redis keys.
* @param schemaDef Defines all of the fields for the Schema and how they are mapped to Redis.
* @param options Additional options for this Schema.
*/
constructor(schemaName: string, schemaDef: SchemaDefinition<T>, options?: SchemaOptions) {
this.#schemaName = schemaName
this.#definition = schemaDef
this.#options = options
this.#validateOptions()
this.#createFields()
}
/**
* The name of the schema. Prefixes the ID when creating Redis keys. Combined
* with the results of idStrategy to generate a key. If name is `foo` and
* idStrategy returns `12345` then the generated key would be `foo:12345`.
*/
get schemaName(): string {
return this.#schemaName
}
/** The {@link Field | Fields} defined by this Schema. */
get fields(): Field[] {
return Object.entries(this.#fieldsByName).map(([_name, field]) => field)
}
/**
* Gets a single {@link Field} defined by this Schema.
*
* @param name The name of the {@link Field} in this Schema.
* @returns The {@link Field}, or null of not found.
*/
fieldByName(name: EntityKeys<T>): Field | null {
return this.#fieldsByName[name] ?? null
}
/** The configured name for the RediSearch index for this Schema. */
get indexName(): string { return this.#options?.indexName ?? `${this.schemaName}:index` }
/** The configured name for the RediSearch index hash for this Schema. */
get indexHashName(): string { return this.#options?.indexHashName ?? `${this.schemaName}:index:hash` }
/**
* The configured data structure, a string with the value of either `HASH` or `JSON`,
* that this Schema uses to store {@link Entity | Entities} in Redis.
*/
get dataStructure(): DataStructure { return this.#options?.dataStructure ?? 'JSON' }
/**
* The configured usage of stop words, a string with the value of either `OFF`, `DEFAULT`,
* or `CUSTOM`. See {@link SchemaOptions} for more details.
*/
get useStopWords(): StopWordOptions { return this.#options?.useStopWords ?? 'DEFAULT' }
/**
* The configured stop words. Ignored if {@link Schema.useStopWords} is anything other
* than `CUSTOM`.
*/
get stopWords(): Array<string> { return this.#options?.stopWords ?? [] }
/**
* Generates a unique string using the configured {@link IdStrategy}.
*
* @returns The generated id.
*/
async generateId(): Promise<string> {
const ulidStrategy = () => ulid()
return await (this.#options?.idStrategy ?? ulidStrategy)();
}
/**
* A hash for this Schema that is used to determine if the Schema has been
* changed when calling {@link Repository#createIndex}.
*/
get indexHash(): string {
const data = JSON.stringify({
definition: this.#definition,
prefix: this.schemaName,
indexName: this.indexName,
indexHashName: this.indexHashName,
dataStructure: this.dataStructure,
useStopWords: this.useStopWords,
stopWords: this.stopWords
})
return createHash('sha1').update(data).digest('base64')
}
#createFields() {
const entries = Object.entries(this.#definition) as [EntityKeys<T>, FieldDefinition][];
return entries.forEach(([fieldName, fieldDef]) => {
const field = new Field(String(fieldName), fieldDef)
this.#validateField(field)
this.#fieldsByName[fieldName] = field
})
}
#validateOptions() {
const { dataStructure, useStopWords } = this
if (dataStructure !== 'HASH' && dataStructure !== 'JSON')
throw new InvalidSchema(`'${dataStructure}' in an invalid data structure. Valid data structures are 'HASH' and 'JSON'.`)
if (useStopWords !== 'OFF' && useStopWords !== 'DEFAULT' && useStopWords !== 'CUSTOM')
throw new InvalidSchema(`'${useStopWords}' in an invalid value for stop words. Valid values are 'OFF', 'DEFAULT', and 'CUSTOM'.`)
if (this.#options?.idStrategy && typeof this.#options.idStrategy !== 'function')
throw new InvalidSchema("ID strategy must be a function that takes no arguments and returns a string.")
if (this.schemaName === '') throw new InvalidSchema(`Schema name must be a non-empty string.`)
if (this.indexName === '') throw new InvalidSchema(`Index name must be a non-empty string.`)
}
#validateField(field: Field) {
const { type } = field
if (type !== 'boolean' && type !== 'date' && type !== 'number' && type !== 'number[]' && type !== 'point' &&
type !== 'string' && type !== 'string[]' && type !== 'text')
throw new InvalidSchema(`The field '${field.name}' is configured with a type of '${field.type}'. Valid types include 'boolean', 'date', 'number', 'number[]', 'point', 'string', 'string[]', and 'text'.`)
if (type === 'number[]' && this.dataStructure === 'HASH')
throw new InvalidSchema(`The field '${field.name}' is configured with a type of '${field.type}'. This type is only valid with a data structure of 'JSON'.`)
}
}
export type InferSchema<T> = T extends Schema<infer R> ? R : never;