-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathcache.ts
75 lines (61 loc) · 2.44 KB
/
cache.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
import avro, { ForSchemaOptions, types } from 'avsc'
import { RawSchema, Schema, SchemaRef } from './@types'
export default class Cache {
registryIdBySubject: { [key: string]: number }
schemasByRegistryId: { [key: string]: Schema }
registryIdBySchemaRef: { [key: string]: number }
forSchemaOptions?: Partial<ForSchemaOptions>
constructor(forSchemaOptions?: Partial<ForSchemaOptions>) {
this.registryIdBySubject = {}
this.schemasByRegistryId = {}
this.registryIdBySchemaRef = {}
this.forSchemaOptions = forSchemaOptions
}
private schemaKeyGen = ({ subject, version }: SchemaRef): string => `${subject}:${version}`
getRegistryIdBySchemaRef = (schema: SchemaRef): number =>
this.registryIdBySchemaRef[this.schemaKeyGen(schema)]
setRegistryIdBySchemaRef = (schema: SchemaRef, registryId: number) => {
this.registryIdBySchemaRef[this.schemaKeyGen(schema)] = registryId
return this.registryIdBySchemaRef[this.schemaKeyGen(schema)]
}
getLatestRegistryId = (subject: string): number | undefined => this.registryIdBySubject[subject]
setLatestRegistryId = (subject: string, id: number): number => {
this.registryIdBySubject[subject] = id
return this.registryIdBySubject[subject]
}
getSchema = (registryId: number): Schema => this.schemasByRegistryId[registryId]
setSchema = (
registryId: number,
schema: RawSchema,
logicalTypesExtra: Record<string, new () => types.LogicalType> = {},
) => {
// @ts-ignore TODO: Fix typings for Schema...
this.schemasByRegistryId[registryId] = avro.Type.forSchema(schema, {
...this.forSchemaOptions,
typeHook:
this.forSchemaOptions?.typeHook ||
function(attr, opts) {
if (typeof attr == 'string') {
if (attr in opts.logicalTypes) {
return (opts.logicalTypes[attr] as unknown) as avro.Type
}
// if we map this as 'namespace.type'.
const qualifiedName = `${opts.namespace}.${attr}`
if (qualifiedName in opts.logicalTypes) {
return (opts.logicalTypes[qualifiedName] as unknown) as avro.Type
}
}
return (undefined as unknown) as avro.Type
},
logicalTypes: {
...this.forSchemaOptions?.logicalTypes,
...logicalTypesExtra,
},
})
return this.schemasByRegistryId[registryId]
}
clear = (): void => {
this.registryIdBySubject = {}
this.schemasByRegistryId = {}
}
}