-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcontext.ts
63 lines (48 loc) · 1.46 KB
/
context.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
import { Transformer } from './transformer'
import { Options, DocumentObject } from './types'
import { JsonApiFractalError } from './errors'
export type Context<TEntity, TExtraProperties = unknown> = {
input: TEntity | undefined
transformer: Transformer<TEntity, TExtraProperties>
included: boolean
options: Options<TExtraProperties>
}
export class ContextBuilder<TEntity, TExtraProperties = unknown> {
input?: TEntity
transformer?: Transformer<TEntity, TExtraProperties>
included = false
options?: Options<TExtraProperties>
constructor(protected renderFunction: (c: Context<TEntity, TExtraProperties>) => DocumentObject) {}
withInput(input: TEntity) {
this.input = input
return this
}
withTransformer(transformer: Transformer<TEntity, TExtraProperties>) {
this.transformer = transformer
return this
}
withIncluded(included: boolean) {
this.included = included
return this
}
withOptions(options: Options<TExtraProperties>) {
this.options = options
return this
}
toContext(): Context<TEntity, TExtraProperties> {
const transformer = this.transformer
if (!transformer) {
throw new JsonApiFractalError('transformer is required')
}
const options = this.options || ({} as Options<TExtraProperties>)
return {
input: this.input,
transformer,
included: this.included,
options,
}
}
serialize(): DocumentObject {
return this.renderFunction(this.toContext())
}
}