-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (63 loc) · 1.97 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
/* a8cgmposts */
const express = require( 'express' );
const app = express();
const _ = require( 'lodash' );
// Config stuffs
const wpcom = require( 'wpcom' )( process.env.WPCOM_TOKEN );
const siteUrl = 'a8cgmposts.wordpress.com';
const site = wpcom.site( siteUrl );
const lastUpdatedWidget = 'text-3';
function updateTimestamp( time ) {
return site.wpcom.req.post(`/sites/${siteUrl}/widgets/widget:${lastUpdatedWidget}`, { settings: { text: time.toISOString() } } );
}
function getLastUpdateTime() {
return site.wpcom.req.get(`/sites/${siteUrl}/widgets/widget:${lastUpdatedWidget}` );
}
app.get( '/', ( req, res ) => {
const updateTime = new Date();
getLastUpdateTime()
.then( ( response ) => {
return response.settings.text;
} )
.then( ( time ) => {
return site.wpcom.req.get( `/read/tags/a8cgm/posts?after=${ time }`, { apiVersion: '1.2' } );
} )
.then( ( response ) => {
return new Promise( ( resolve, reject ) => {
// If there is no data, or no posts, return.
if ( ! response || response.number === 0 ) {
resolve();
}
// Create posts.
_.each( response.posts, ( post, i ) => {
// Pictures are neat, lets use either the featured image or attachments in the original post.
let photos = [];
if ( post.featured_image && post.featured_image.length ) {
photos.push( post.featured_image );
} else {
photos = _.map( post.attachments, 'URL' );
}
site.addPost( {
title: post.title,
content: post.excerpt + `\n\n<a href="${ post.URL }">${ post.URL }</a>`,
publicize_message: `${ post.title } ${ post.short_URL }`,
media_urls: photos
} )
.then( () => {
// if this is the last post, resolve promise.
if ( i === ( response.number - 1 ) ) {
resolve();
}
} );
} );
} );
} )
.then( ( message ) => {
// Update our last run time.
return updateTimestamp( updateTime );
} )
.then( () => {
res.send( 'great success' );
} )
} );
app.listen( 5000 );