-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWrapperBuilder.ts
309 lines (287 loc) · 11.6 KB
/
WrapperBuilder.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { IAdapter } from "./adapter/IAdapter.ts";
import { IProxyAdapter } from "./adapter/IProxyAdapter.ts";
import { DirDescriptor, PathInfo } from "./DirDescriptor.ts";
import { IServiceConfig } from "./IServiceConfig.ts";
import { Message, MessageMethod } from "./Message.ts";
import { resolvePathPatternWithUrl } from "./PathPattern.ts";
import { Service, ServiceFunction } from "./Service.ts";
import { transformation } from "./transformation/transformation.ts";
import { Url } from "./Url.ts";
import { pathCombine, slashTrim, upToLast } from "./utility/utility.ts";
export type MapUrl = string | ((msg: Message) => string | [ string, MessageMethod ]);
export type Transform<TConfig> = any | ((msg: Message, config: TConfig, json: any) => any);
// Tools for automating adding standard API patterns to a Service which wraps an underlying API
const applyMapUrl = (mapUrl: MapUrl, msg: Message, config: IServiceConfig, createTest?: (msg: Message) => boolean, createMapUrl?: MapUrl): [ string, MessageMethod ] | Message => {
if (createTest && createMapUrl) {
if (createTest(msg)) mapUrl = createMapUrl;
}
if (typeof mapUrl === 'string') {
return [ resolvePathPatternWithUrl(mapUrl, msg.url, config) as string, msg.method ];
} else {
const mappedUrl = mapUrl(msg);
if (typeof mappedUrl === 'string') return msg.setStatus(400, mappedUrl);
const [ url, method ] = mappedUrl;
return [ resolvePathPatternWithUrl(url, msg.url, config) as string, method ];
}
};
const applyTransform = async <TConfig extends IServiceConfig = IServiceConfig>(transform: Transform<TConfig>, resp: Message, config: TConfig) => {
if (!resp.ok || !resp.data) return resp;
const json = await resp.data.asJson();
if (transform) {
if (typeof transform == "function") {
return transform(json, resp, config);
} else {
try {
return transformation(transform, { json, config, resp }, resp.url);
} catch (err) {
if (err instanceof SyntaxError) {
const errx = err as SyntaxError & { filename: string };
return resp.setStatus(400, `${errx.message} at: ${errx.filename} cause: ${errx.cause}`);
}
}
}
} else {
return await resp.data.asJson();
}
}
export const schemaInstanceMime = (url: Url) => {
const schemaUrl = pathCombine(url.baseUrl(), upToLast(url.servicePath, '/'), ".schema.json");
return `application/json; schema="${schemaUrl}"`;
};
export interface BuildDefaultDirectoryParams<TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig> {
basePath: string;
service: Service<TAdapter, TConfig>;
}
/**
* Build a default directory handler that lists only other registered subdirectories
* @param {string} basePath - The base path of the handler relative to the base path of the service
* @param {Service<TAdapter, TConfig>} service - The service to which to add the handler
* */
export const buildDefaultDirectory = <TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig>({
basePath,
service
}: BuildDefaultDirectoryParams<TAdapter, TConfig>
) => {
service.getDirectoryPath(basePath, (msg) => {
const dirJson = {
path: msg.url.servicePath,
// add in subdirectory paths already registered on the service
paths: service.pathsAt(basePath),
spec: {
pattern: "view",
respMimeType: "text/plain"
}
} as DirDescriptor;
msg.setDataJson(dirJson);
msg.data!.setIsDirectory();
return Promise.resolve(msg);
});
}
export interface BuildStoreParams<TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig> {
basePath: string;
service: Service<TAdapter, TConfig>;
schema: Record<string, unknown>;
mapUrlRead?: MapUrl;
mapUrlWrite?: MapUrl;
mapUrlDelete?: MapUrl;
createTest?: (msg: Message) => boolean;
mapUrlCreate?: MapUrl;
mapUrlDirectoryRead?: MapUrl | null;
mapUrlDirectoryDelete?: MapUrl;
transformDirectory?: Transform<TConfig>;
transformRead?: Transform<TConfig>;
transformWrite?: Transform<TConfig>;
}
/**
* Build a store pattern on a given base path of a service
* @param {string} basePath - The base path of the store relative to the base path of the service
* @param {Service<TAdapter, TConfig>} service - The service to which to add the store pattern
* @param {Record<string, unknown>} schema - The schema of data stored
* @param {MapUrl} mapUrlRead - Map the called url into the underlying API url for read
* @param {MapUrl} mapUrlWrite - Map the called url into the underlying API url for write
* @param {MapUrl} mapUrlDelete - Map the called url into the underlying API url for deletion
* @param {[ (msg: Message) => boolean, MapUrl ]} mapUrlCreate - Map the called url into the underlying API url for creation
* @param {MapUrl | null} mapUrlDirectoryRead - Map the called url into the underlying API url for reading a directory. If null, don't call the underlying API, the directory is supplied by transformDirectory.
* @param {MapUrl} mapUrlDirectoryDelete - Map the called url into the underlying API url for directory deletion
* @param {Transform<TConfig>} transformDirectory - Transform the directory list from the underlying API
* @param {Transform<TConfig>} transformRead - Transform the read data from the underlying API
* @param {Transform<TConfig>} transformWrite - Transform the incoming data for writing as appropriate for the underlying API
* */
export const buildStore = <TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig>({
basePath,
service,
schema,
mapUrlRead,
mapUrlWrite,
mapUrlDelete,
createTest,
mapUrlCreate,
mapUrlDirectoryRead,
mapUrlDirectoryDelete,
transformDirectory,
transformRead,
transformWrite
}: BuildStoreParams<TAdapter, TConfig>
) => {
service.getDirectoryPath(basePath, async (msg, context, config) => {
if (mapUrlDirectoryRead === undefined) return msg.setStatus(500, 'No mapping for directory read configured when building store');
let dirJson: Message | DirDescriptor;
if (mapUrlDirectoryRead !== null) {
const transformedUrl = applyMapUrl(mapUrlDirectoryRead, msg, config);
if (transformedUrl instanceof Message) return transformedUrl;
const [ url, method ] = transformedUrl;
const reqMsg = new Message(url, context.tenant, method, msg);
reqMsg.startSpan();
const dirResp = await context.makeProxyRequest!(reqMsg);
dirJson = await applyTransform(transformDirectory, dirResp, config) as DirDescriptor | Message;
} else {
if (typeof transformDirectory !== 'function') {
return msg.setStatus(400, 'buildStore wrongly configured with null mapUrlDirectoryRead and non-function transformDirectory');
}
// in this case, transformDirectory gets the directory paths
dirJson = await transformDirectory({}, msg, config, context);
}
if (dirJson instanceof Message) return dirJson;
dirJson.path = msg.url.servicePath;
const dirPath = pathCombine(basePath, msg.url.servicePath);
// add in subdirectory paths already registered on the service
dirJson.paths.push(...service.pathsAt(dirPath));
dirJson.spec = {
pattern: "store",
storeMimeTypes: [ schemaInstanceMime(msg.url) ],
createDirectory: false,
createFiles: true,
exceptionMimeTypes: {
"/.schema.json": [ "application/schema+json", "" ]
}
};
msg.setDataJson(dirJson);
msg.data!.setIsDirectory();
return msg;
});
const mapPath: (mapUrl: MapUrl,
transformRead: any,
transformWrite: any,
createTest?: (msg: Message) => boolean,
mapUrlCreate?: MapUrl) => ServiceFunction<TAdapter, TConfig> =
(mapUrl: MapUrl,
transformRead: any,
transformWrite: any,
createTest?: (msg: Message) => boolean,
mapUrlCreate?: MapUrl) => async (msg, context, config) =>
{
// return schema from req for .schema.json on any resource path
if (msg.url.resourceName === ".schema.json" && msg.method === "GET") {
return msg.setDataJson(schema, "application/schema+json");
}
const mappedUrl = applyMapUrl(mapUrl, msg, config, createTest, mapUrlCreate);
if (mappedUrl instanceof Message) return mappedUrl;
const [ url, method ] = mappedUrl;
const reqMsg = new Message(url, context.tenant, method, msg);
reqMsg.startSpan();
if (msg.method === "PUT" || msg.method === "POST") {
if (!msg.data) return msg.setStatus(400, "No body in write operation");
if (transformWrite) {
let writeJson = await msg.data.asJson();
writeJson = transformation(transformWrite, writeJson, msg.url);
reqMsg.setDataJson(writeJson, "application/json");
} else {
reqMsg.setData(msg.data!.data, msg.data!.mimeType);
}
}
const resp = await context.makeProxyRequest!(reqMsg);
if (!resp.ok) {
await resp.data?.ensureDataIsArrayBuffer();
return resp;
}
if (msg.method === "GET") {
if (!resp.data) return resp.setStatus(400, "No body in GET response");
if (transformRead) {
const json = await applyTransform(transformRead, resp, config);
if (json instanceof Message) return json;
resp.setDataJson(json, "application/json");
} else {
const mimeType = schemaInstanceMime(msg.url);
resp.data.setMimeType(mimeType);
}
} else {
resp.data = undefined;
}
return resp;
};
if (mapUrlRead) service.getPath(basePath, mapPath(mapUrlRead, transformRead, undefined));
if (mapUrlWrite) service.putPath(basePath, mapPath(mapUrlWrite, undefined, transformWrite, createTest, mapUrlCreate));
if (mapUrlDelete) service.deletePath(basePath, mapPath(mapUrlDelete, undefined, undefined));
if (mapUrlDirectoryDelete) service.deleteDirectoryPath(basePath, mapPath(mapUrlDirectoryDelete, undefined, undefined));
}
export interface BuildStateMapParams<TData, TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig> {
basePath: string;
service: Service<TAdapter, TConfig>;
stateData: Record<string, TData>;
readOnly?: boolean;
schema: any;
}
export const buildStateMap = <TData, TAdapter extends IAdapter = IAdapter, TConfig extends IServiceConfig = IServiceConfig>({
basePath,
service,
stateData,
readOnly,
schema
}: BuildStateMapParams<TData, TAdapter, TConfig>) => {
service.getDirectoryPath(basePath, (msg) => {
let dirJson: DirDescriptor;
const ensureLeadingSlash = (s: string) => s.startsWith('/') ? s : '/' + s;
const paths = Object.keys(stateData).map(key => [ ensureLeadingSlash(key) ] as PathInfo);
if (readOnly === false) {
dirJson = {
path: msg.url.servicePath,
paths,
spec: {
pattern: "store",
storeMimeTypes: [ schemaInstanceMime(msg.url) ],
createDirectory: false,
createFiles: true,
exceptionMimeTypes: {
".json.schema": [ "application/schema+json", "" ]
}
}
};
} else {
dirJson = {
path: msg.url.servicePath,
paths,
spec: {
pattern: "view",
respMimeType: schemaInstanceMime(msg.url)
}
};
}
msg.setDataJson(dirJson);
msg.data!.setIsDirectory();
return Promise.resolve(msg);
});
service.getPath(basePath, (msg) => {
if (msg.url.resourceName === ".schema.json" && msg.method === "GET") {
return Promise.resolve(msg.setDataJson(schema, "application/schema+json"));
}
const val = stateData[msg.url.resourcePath] || stateData[slashTrim(msg.url.resourcePath)];
if (!val) {
return Promise.resolve(msg.setStatus(404, 'Not found'));
} else {
return Promise.resolve(msg.setDataJson(val, schemaInstanceMime(msg.url)));
}
});
if (readOnly === false) {
const writePath: ServiceFunction<TAdapter, TConfig> = (msg) => {
if (!msg.data) return Promise.resolve(msg.setStatus(400, 'No data to write'));
const item = stateData[msg.url.resourcePath] || stateData[slashTrim(msg.url.resourcePath)];
if (!item) {
return Promise.resolve(msg.setStatus(404, 'Not found'));
} else {
return Promise.resolve(msg.setDataJson(item, schemaInstanceMime(msg.url)));
}
}
service.postPath(basePath, writePath);
service.putPath(basePath, writePath);
}
}