-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
63 lines (50 loc) · 1.44 KB
/
index.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
import axios from 'axios';
import { Handler, APIGatewayEvent } from 'aws-lambda';
interface GhostObject {
slug?: string;
url?: string;
}
interface GhostWebhookObject {
current: GhostObject;
previous: GhostObject;
}
interface GhostWebhookPayload {
page?: GhostWebhookObject;
post?: GhostWebhookObject;
}
interface CloudflarePurgeFilesResponse {
success: boolean;
}
const cfId = process.env.CLOUDFLARE_IDENTIFIER;
const cfApiToken = process.env.CLOUDFLARE_API_TOKEN;
const ghostUrl = process.env.GHOST_URL;
function getFilesFromPayload(payload: GhostWebhookPayload) {
const object = payload.page || payload.post;
if (!object) {
return [];
}
const files = [];
for (const state of ['current', 'previous']) {
if (object[state].url) {
files.push(object[state].url);
} else if (object[state].slug) {
files.push(ghostUrl + object[state].slug);
}
}
}
export const handler: Handler<APIGatewayEvent> = async (event) => {
const files = [ghostUrl];
if (event.body) {
const payload: GhostWebhookPayload = JSON.parse(event.body);
files.concat(getFilesFromPayload(payload));
}
const response = await axios.post<CloudflarePurgeFilesResponse>(
`https://api.cloudflare.com/client/v4/zones/${cfId}/purge_cache`,
{ files },
{ headers: { 'Authorization': `Bearer ${cfApiToken}` } }
);
if (!response.data.success) {
throw new Error(JSON.stringify(response.data));
}
return response.data;
};