@@ -12,28 +12,41 @@ const subName = `add-post-to-db${config.env === 'production' ? '' : `-${config.e
12
12
const topic = pubsub . topic ( topicName ) ;
13
13
const subscription = topic . subscription ( subName ) ;
14
14
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
+
15
33
export default ( ) => subscription . get ( { autoCreate : true } )
16
34
. then ( ( ) => {
17
35
logger . info ( `waiting for messages in ${ topicName } ` ) ;
18
36
subscription . on ( 'message' , ( message ) => {
19
37
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` ) ;
21
39
data . publishedAt = new Date ( data . publishedAt ) ;
22
40
data . createdAt = new Date ( ) ;
23
41
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 ) )
34
43
. then ( ( ) => {
35
- logger . info ( `added successfully post ${ data . id } ` ) ;
44
+ logger . info ( { post : data } , `added successfully post ${ data . id } ` ) ;
36
45
message . ack ( ) ;
46
+ } )
47
+ . catch ( ( err ) => {
48
+ logger . error ( { post : data , err } , 'failed to add post to db' ) ;
49
+ message . nack ( ) ;
37
50
} ) ;
38
51
} ) ;
39
52
} ) ;
0 commit comments