-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponseMeta.test.ts
83 lines (75 loc) · 2.14 KB
/
responseMeta.test.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
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { routerToServerAndClient } from './__testHelpers';
import fetch from 'node-fetch';
import * as trpc from '../src';
test('set custom headers in beforeEnd', async () => {
const onError = jest.fn();
const { close, httpUrl } = routerToServerAndClient(
trpc
.router<trpc.CreateHttpContextOptions>()
.query('public.q', {
resolve() {
return 'public endpoint';
},
})
.query('nonCachedEndpoint', {
resolve() {
return 'not cached endpoint';
},
}),
{
server: {
onError,
responseMeta({ ctx, paths, type, errors }) {
// assuming you have all your public routes with the kewyord `public` in them
const allPublic =
paths && paths.every((path) => path.includes('public'));
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === 'query';
if (ctx?.res && allPublic && allOk && isQuery) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
},
},
);
{
const res = await fetch(`${httpUrl}/public.q`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"id": null,
"result": Object {
"data": "public endpoint",
"type": "data",
},
}
`);
expect(res.headers.get('cache-control')).toMatchInlineSnapshot(
`"s-maxage=1, stale-while-revalidate=86400"`,
);
}
{
const res = await fetch(`${httpUrl}/nonCachedEndpoint`);
expect(await res.json()).toMatchInlineSnapshot(`
Object {
"id": null,
"result": Object {
"data": "not cached endpoint",
"type": "data",
},
}
`);
expect(res.headers.get('cache-control')).toBeNull();
}
close();
});