-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathdynamo-provider.ts
More file actions
98 lines (85 loc) · 2.36 KB
/
dynamo-provider.ts
File metadata and controls
98 lines (85 loc) · 2.36 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
89
90
91
92
93
94
95
96
97
98
import { readFileSync } from "node:fs";
import { createGenericHandler } from "../core/createGenericHandler.js";
import { resolveTagCache } from "../core/resolve.js";
const PHYSICAL_RESOURCE_ID = "dynamodb-cache" as const;
//TODO: modify this, we should use the same format as the cache
type DataType = {
tag: {
S: string;
};
path: {
S: string;
};
revalidatedAt: {
N: string;
};
/**
* The time at which the tag should be considered stale, in milliseconds since epoch.
*/
stale?: {
N: string;
};
/**
* The time at which the tag should expire, in milliseconds since epoch.
*/
expire?: {
N: string;
};
};
export interface InitializationFunctionEvent {
type: "initializationFunction";
requestType: "create" | "update" | "delete";
resourceId: typeof PHYSICAL_RESOURCE_ID;
}
const tagCache = await resolveTagCache(
globalThis.openNextConfig?.initializationFunction?.tagCache,
);
export const handler = await createGenericHandler({
handler: defaultHandler,
type: "initializationFunction",
});
async function defaultHandler(
event: InitializationFunctionEvent,
): Promise<InitializationFunctionEvent> {
switch (event.requestType) {
case "delete":
return remove();
default:
return insert(event.requestType);
}
}
async function insert(
requestType: InitializationFunctionEvent["requestType"],
): Promise<InitializationFunctionEvent> {
// If it is in nextMode, we don't need to do anything
if (tagCache.mode === "nextMode") {
return {
type: "initializationFunction",
requestType,
resourceId: PHYSICAL_RESOURCE_ID,
};
}
const file = readFileSync("dynamodb-cache.json", "utf8");
const data: DataType[] = JSON.parse(file);
const parsedData = data.map((item) => ({
tag: item.tag.S,
path: item.path.S,
revalidatedAt: Number.parseInt(item.revalidatedAt.N),
...(item.stale && { stale: Number.parseInt(item.stale.N) }),
...(item.expire && { expire: Number.parseInt(item.expire.N) }),
}));
await tagCache.writeTags(parsedData);
return {
type: "initializationFunction",
requestType,
resourceId: PHYSICAL_RESOURCE_ID,
};
}
async function remove(): Promise<InitializationFunctionEvent> {
// Do we want to actually delete anything here?
return {
type: "initializationFunction",
requestType: "delete",
resourceId: PHYSICAL_RESOURCE_ID,
};
}