Created
July 27, 2018 09:09
-
-
Save kmelve/42b5df41149753dbf76e27b864f598b8 to your computer and use it in GitHub Desktop.
Serverless task for updating slack about new photos in https://codepen.io/kmelve/pen/VdqPbV?editors=0010
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
| require('babel-polyfill'); | |
| const SanityClient = require('@sanity/client'); | |
| const axios = require('axios'); | |
| const client = SanityClient({ | |
| projectId: 'anokeucs', | |
| dataset: 'sanitycsstricks', | |
| useCdn: false | |
| }) | |
| /** | |
| * @param context {WebtaskContext} | |
| */ | |
| module.exports = async function(context, cb) { | |
| const { created, updated, deleted } = context.body.ids; | |
| const query = async ids => client.fetch(`*[_id in [${ids.map(JSON.stringify).join(',')}]]{_id,url}`); | |
| const data = { | |
| new: created.length && await query(created), | |
| updated: updated.length && await query(updated), | |
| deleted | |
| }; | |
| console.log(JSON.stringify(data, undefined, 2)); | |
| const { SLACK_WEBHOOK_URL, SANITY_TOKEN } = context.secrets; | |
| const messages = payload => Object.keys(payload).filter(key => payload[key]).reduce((acc, key) => { | |
| const actionData = payload[key]; | |
| if(key === 'deleted' && actionData.length) { | |
| return [...acc, { | |
| title: 'photo(s) deleted:', | |
| text: actionData.map(_id => _id).join(' '), | |
| short: true | |
| }]; | |
| } | |
| return [...acc, ...actionData.map(image => ({ | |
| title: `${image._id} was ${key}:`, | |
| image_url: image.url, | |
| text: `\`\`\`curl 'https://anokeucs.api.sanity.io/v1/data/mutate/sanitycsstricks' -H 'Accept: application/json' -H 'Content-Type: application/json' --data-binary '{"mutations":[{"delete":{"id":"${image._id}"}}]}' -H "Authorization: Bearer ${SANITY_TOKEN}" --compressed\`\`\`` | |
| }))]; | |
| }, []); | |
| const options = { | |
| text: "Something happened with the photo map", | |
| attachments: [ ...messages(data)] | |
| }; | |
| console.log(JSON.stringify(options, undefined, 2)) | |
| return axios.post(SLACK_WEBHOOK_URL, JSON.stringify(options)).then((response) => { | |
| console.log('SUCCEEDED: Sent slack webhook: \n', response.data); | |
| cb(null, { hello: context.query.name || 'Anonymous' }); | |
| }).catch((error) => { | |
| console.log('FAILED: Send slack webhook', error); | |
| cb(null, { hello: context.query.name || 'Anonymous' }); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment