-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.ts
More file actions
88 lines (77 loc) · 1.89 KB
/
example.ts
File metadata and controls
88 lines (77 loc) · 1.89 KB
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
import { createTransformer } from "./main";
type User = {
id: string;
createdAt: number;
username: string;
password: string;
friends: User[];
};
declare const user: User;
declare const formatDate: (ts: number, tz?: string) => string;
declare const db: {
fetchRole: (id: string) => Promise<"admin" | "moderator">;
};
const admin = createTransformer<User>()
.setModelConfig({
"*": true,
friends: false,
})
// Add new fields. Promises will be executed in parallel!
.setCustomConfig({ role: (user) => db.fetchRole(user.id) });
const forAdmin = await admin.transform(user);
/*
* {
* id: string;
* createdAt: number;
* username: string;
* password: string;
* role: "admin" | "moderator";
* }
*/
const moderator = admin.setModelConfig({
password: false,
});
const forModerator = await moderator.transform(user);
/*
* {
* id: string;
* createdAt: number;
* username: string;
* role: "admin" | "moderator";
* }
*/
const basePublicUser = createTransformer<
User,
{ timezone: string }
>().setModelConfig({
"*": true,
password: false,
// pass on additional context that will be used for transformation
createdAt: (user, ctx) => formatDate(user.createdAt, ctx.timezone),
});
const publicUser = basePublicUser.setModelConfig({
// use nested transformers for single values or arrays
friends: basePublicUser,
});
const forPublic = await publicUser.transform(user, {
timezone: "Europe/Lisbon",
});
/**
* {
* id: string;
* username: string;
* createdAt: string;
* friends: {
* id: string;
* username: string;
* createdAt: string;
* friends: ...[];
* }[];
* }
*/
import type { TransformerResult } from "./main";
const dateSerializer = createTransformer<User>().setModelConfig({
createdAt: (user) => formatDate(user.createdAt),
});
type SerializedDate = TransformerResult<typeof dateSerializer>;
// { createdAt: string }