Created
August 31, 2019 08:26
-
-
Save alexesDev/1f928bcab38b5b86541e1fec99382702 to your computer and use it in GitHub Desktop.
Обновление хуков moysklad.ru
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = require('node-fetch'); | |
const MoyskladCore = require('moysklad'); | |
const MoyskladQueueExtension = require('moysklad-extension-queue'); | |
const { loadRows } = require('moysklad-tools'); | |
const { readFileSync } = require('fs'); | |
const Moysklad = MoyskladCore.compose(MoyskladQueueExtension); | |
const ms = Moysklad({ | |
queue: true, | |
fetch, | |
}); | |
const localItems = JSON.parse(readFileSync('./webhooks.json').toString()); | |
function compareItem(a, b) { | |
return a.entityType == b.entityType && a.action == b.action; | |
} | |
async function run() { | |
const options = { limit: 100 }; | |
const webhooks = await ms.GET('entity/webhook', options); | |
const remoteItems = await loadRows(ms, webhooks, options); | |
const newItems = localItems.filter(li => !remoteItems.some(ri => compareItem(li, ri))); | |
const oldItems = remoteItems.filter(ri => !localItems.some(li => compareItem(li, ri))); | |
const updatedItems = remoteItems.filter(li => localItems.some(ri => compareItem(li, ri) && li.url !== ri.url)); | |
console.log('newItems:', newItems); | |
console.log('oldItems:', oldItems); | |
console.log('updatedItems:', updatedItems); | |
const getNewFields = oldItem => { | |
const newItem = localItems.find(i => compareItem(i, oldItem)); | |
return { url: newItem.url }; | |
}; | |
return Promise.all([ | |
...newItems.map(i => ms.POST('entity/webhook', i)), | |
...oldItems.map(i => ms.DELETE(['entity/webhook', i.id])), | |
...updatedItems.map(i => ms.PUT(['entity/webhook', i.id], getNewFields(i))), | |
]); | |
} | |
run() | |
.then(() => console.log('done')) | |
.catch(err => console.log(err.message)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[{ | |
"url": "https://c8a83d0c.ngrok.io",[{ | |
"url": "https://c8a83d0c.ngrok.io", | |
"action": "CREATE", | |
"entityType": "customerorder" | |
}, { | |
"url": "https://c8a83d0c.ngrok.io/test", | |
"action": "DELETE", | |
"entityType": "customerorder" | |
}] | |
"action": "CREATE", | |
"entityType": "customerorder" | |
}, { | |
"url": "https://c8a83d0c.ngrok.io/test", | |
"action": "DELETE", | |
"entityType": "customerorder" | |
}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment