-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync-stores.js
101 lines (88 loc) · 3.06 KB
/
sync-stores.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
98
99
100
101
'use strict';
const config = require( 'config' );
const DABC = require( './dabc' );
const WooCommerceAPI = require( 'woocommerce-api' );
const UntappdClient = require( 'node-untappd' );
const querystring = require( 'querystring' );
const PromisePool = require( 'promise-pool-executor' );
const _ = require( 'lodash' );
const WooCommerce = new WooCommerceAPI( {
url: config.get( 'woocommerce.url' ),
consumerKey: config.get( 'woocommerce.key' ),
consumerSecret: config.get( 'woocommerce.secret' ),
wpAPI: true,
version: 'wp/v2',
} );
const getStoreMapByNumber = ( number ) => new Promise( ( resolve, reject ) => {
WooCommerce.get(
'stores?' + querystring.stringify( { slug: `store-${number}` } ),
( err, res, body ) => {
if ( err ) {
reject( err );
} else {
try {
const json = JSON.parse( body );
resolve( json );
} catch ( syntaxError ) {
console.error( body );
reject( syntaxError );
}
}
}
);
} );
const addNewStore = ( storeToCreate ) => new Promise( ( resolve, reject ) => {
const storeMapData = {
name: storeToCreate.label,
latitude: storeToCreate.latitude,
longitude: storeToCreate.longitude,
info_window: [
`<strong>Address:</strong> ${storeToCreate.address01}<br/>${storeToCreate.address02}`,
`<strong>Phone:</strong> ${storeToCreate.phone}`,
`<strong>Manager:</strong> ${storeToCreate.manager}`,
`<strong>Store Hours:</strong> ${storeToCreate.hours}`,
].join( '<br/>' ),
};
console.log( `Creating map for ${storeToCreate.label}` );
WooCommerce.post(
'stores',
storeMapData,
( err, res, body ) => {
if ( err ) {
reject( err );
} else {
try {
const json = JSON.parse( body );
resolve( json );
} catch ( syntaxError ) {
console.error( body );
reject( syntaxError );
}
}
}
);
} );
DABC.getAllStores( ( err, stores ) => {
console.log( `Found ${stores.length} stores, syncing..` );
// Create a pool with a concurrency limit
const pool = new PromisePool.PromisePoolExecutor( {
frequencyLimit: 10,
frequencyWindow: 1200,
} );
pool.addEachTask( {
data: stores,
generator: ( store ) => {
console.log( `Processing ${store.label}` );
return getStoreMapByNumber( store.storeNumber ).then( results => {
if ( 0 === results.length ) {
return addNewStore( store );
} else {
console.log( store.label + ' already exists.' );
return results[0];
}
} );
}
} ).promise().then( ( results ) => {
console.log( results.length + ' stores processed.' );
} );
} );