Skip to content

Commit dd782d5

Browse files
author
Ido Shamun
committed
fix: handle invalid published time
1 parent d16abe3 commit dd782d5

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

Diff for: src/subscriber.js

+25-12
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,41 @@ const subName = `add-post-to-db${config.env === 'production' ? '' : `-${config.e
1212
const topic = pubsub.topic(topicName);
1313
const subscription = topic.subscription(subName);
1414

15+
const addPost = data =>
16+
post.add(data)
17+
.catch((err) => {
18+
if (err.code === 'ER_NO_REFERENCED_ROW_2') {
19+
return logger.warn(`publication id ${data.publicationId} does not exist`);
20+
}
21+
22+
if (err.code === 'ER_DUP_ENTRY') {
23+
return logger.info(`post ${data.id} already exists`);
24+
}
25+
26+
if (err.code === 'ER_TRUNCATED_WRONG_VALUE') {
27+
return addPost(Object.assign({}, data, { publishedAt: null }));
28+
}
29+
30+
throw err;
31+
});
32+
1533
export default () => subscription.get({ autoCreate: true })
1634
.then(() => {
1735
logger.info(`waiting for messages in ${topicName}`);
1836
subscription.on('message', (message) => {
1937
const data = JSON.parse(Buffer.from(message.data, 'base64').toString());
20-
logger.info(`adding post ${data.id} to db`, data);
38+
logger.info({ post: data }, `adding post ${data.id} to db`);
2139
data.publishedAt = new Date(data.publishedAt);
2240
data.createdAt = new Date();
2341
const props = ['id', 'title', 'url', 'publicationId', 'publishedAt', 'createdAt', 'image', 'ratio', 'placeholder', 'tags', 'siteTwitter', 'creatorTwitter'];
24-
post.add(_.pick(data, props))
25-
.catch((err) => {
26-
if (err.code === 'ER_NO_REFERENCED_ROW_2') {
27-
logger.warn(`publication id ${data.publicationId} does not exist`);
28-
} else if (err.code === 'ER_DUP_ENTRY') {
29-
logger.info(`post ${data.id} already exists`);
30-
} else {
31-
throw err;
32-
}
33-
})
42+
addPost(_.pick(data, props))
3443
.then(() => {
35-
logger.info(`added successfully post ${data.id}`);
44+
logger.info({ post: data }, `added successfully post ${data.id}`);
3645
message.ack();
46+
})
47+
.catch((err) => {
48+
logger.error({ post: data, err }, 'failed to add post to db');
49+
message.nack();
3750
});
3851
});
3952
});

0 commit comments

Comments
 (0)