-
Notifications
You must be signed in to change notification settings - Fork 2
/
json.ts
68 lines (58 loc) · 1.46 KB
/
json.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
/**
* This example shows how to implement a storage returning JSON
*/
import { Readable } from 'node:stream';
import { fastify } from 'fastify';
import type { StorageInfo, StreamRange } from '../src/send-stream';
import { Storage } from '../src/send-stream';
const app = fastify({ exposeHeadRoutes: true });
class JSONStorage extends Storage<StorageInfo<unknown>, Buffer> {
// eslint-disable-next-line @typescript-eslint/require-await
async open(data: StorageInfo<unknown>) {
const buffer = Buffer.from(JSON.stringify(data.attachedData), 'utf8');
return {
...data,
attachedData: buffer,
size: buffer.byteLength,
mimeType: 'application/json',
mimeTypeCharset: 'UTF-8',
};
}
createReadableStream(
storageInfo: StorageInfo<Buffer>,
range: StreamRange | undefined,
autoClose: boolean,
) {
const buffer = range
? storageInfo.attachedData.subarray(range.start, range.end + 1)
: storageInfo.attachedData;
return new Readable({
autoDestroy: autoClose,
read() {
this.push(buffer);
this.push(null);
},
});
}
async close() {
// noop
}
}
const storage = new JSONStorage({ dynamicCompression: true });
app.get('*', async (request, reply) => {
await storage.send(
{
attachedData: { mydata: 'mydata' },
mtimeMs: Date.now(),
},
request.raw,
reply.raw,
);
});
app.listen({ port: 3000 })
.then(() => {
console.info('listening on http://localhost:3000');
})
.catch((err: unknown) => {
console.error(err);
});