-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
97 lines (85 loc) · 2.74 KB
/
index.js
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
const arc = require('@architect/functions')
const logger = require('@architect/shared/logger')
const dataPosts = require('@architect/shared/data-posts')
const { derivePostType } = require('@architect/shared/utils')
const create = require('./create')
const update = require('./update')
const deletePost = require('./delete')
const undelete = require('./undelete')
function setRootProperties (post) {
// set published to utc date without seconds
post.published = new Date(post.properties.published[0]).toISOString().replace(/\.000Z$/, 'Z')
if ('mp-channel' in post.properties) {
post.channel = post.properties['mp-channel'][0]
} else if (!('channel' in post)) {
post.channel = 'posts' // default channel is posts
}
}
function sanitise (post) {
const reservedProperties = ['action', 'access_token', 'h']
for (const prop in post.properties) {
if (prop.startsWith('mp-') || reservedProperties.includes(prop)) {
delete post.properties[prop]
}
if (prop.endsWith('[]')) {
const propModified = prop.slice(0, -2)
post.properties[propModified] = post.properties[prop]
delete post.properties[prop]
}
// remove empty/whitespace strings e.g. name: [""]
if (
Array.isArray(post.properties[prop]) &&
post.properties[prop].length === 1 &&
post.properties[prop][0] === ''
) {
delete post.properties[prop]
}
}
}
async function action (scope, body) {
let res
if (scope === 'create' || scope === 'draft') {
res = await create(scope, body)
} else if (scope === 'update') {
res = await update(body)
} else if (scope === 'delete') {
res = await deletePost(body)
} else if (scope === 'undelete') {
res = await undelete(body)
}
// if the action was successful...
if (res.statusCode < 300) {
// set root properties indexed by ddb
setRootProperties(res.post)
// remove unwanted properties
sanitise(res.post)
// derive the post type
res.post['post-type'] = derivePostType(res.post)
// find syndication options
let syndicateTo
if ('mp-syndicate-to' in body) {
syndicateTo = body['mp-syndicate-to']
} else if (('properties' in body) && ('mp-syndicate-to' in body.properties)) {
syndicateTo = body.properties['mp-syndicate-to']
}
if (syndicateTo && !Array.isArray(syndicateTo)) {
syndicateTo = [syndicateTo]
}
await dataPosts.put(res.post)
logger.info(`${scope.toUpperCase()}D ${res.post.url}`)
// async tasks after post is created/updated
await arc.events.publish({
name: 'process-post',
payload: {
url: res.post.url,
syndicateTo,
scope
}
})
}
return {
statusCode: res.statusCode,
headers: res.headers || {}
}
}
module.exports = { action }