Created
February 22, 2021 21:49
-
-
Save ccondry/5eef2d0fcc35f44f97faa147758842a0 to your computer and use it in GitHub Desktop.
send data as a file to webex user or room using node-fetch
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('dotenv').config() | |
const fetch = require('node-fetch') | |
async function sendWebexFile ({ | |
filename = 'test.csv', | |
fileMetaName = 'files', | |
contentType = 'text/csv', | |
content, | |
metadata = {} | |
}) { | |
try { | |
// build the payload body | |
const boundary = 'xxxxxxxxxx' | |
let data = '' | |
// append each metadata field to the body | |
for(const i in metadata) { | |
if ({}.hasOwnProperty.call(metadata, i)) { | |
data += `--${boundary}\r\n` | |
data += `Content-Disposition: form-data; name="${i}"; \r\n\r\n${metadata[i]}\r\n` | |
} | |
} | |
data += `--${boundary}\r\n` | |
// append the file | |
data += `Content-Disposition: form-data; name="${fileMetaName}"; filename="${filename}"\r\n` | |
// append file content type | |
data += `Content-Type: ${contentType}\r\n\r\n` | |
const body = Buffer.concat([ | |
Buffer.from(data, 'utf8'), | |
Buffer.from(content, 'utf8'), | |
Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8') | |
]) | |
const options = { | |
method: 'POST', | |
headers: { | |
Authorization: 'Bearer ' + process.env.WEBEX_BOT_TOKEN, | |
'Content-Type': `multipart/form-data; boundary=${boundary}` | |
}, | |
body | |
} | |
const url = 'https://webexapis.com/v1/messages' | |
const response = await fetch(url, options) | |
// parse response body | |
const json = await response.json() | |
// check response status code | |
if (response.ok) { | |
return json | |
} else { | |
throw json | |
} | |
} catch (e) { | |
throw e | |
} | |
} | |
async function main () { | |
try { | |
// metadata for the request. these are the other fields of data to send to | |
// webex | |
const metadata = { | |
toPersonEmail: '[email protected]', | |
// roomId: 'your-room-id', | |
text: `here is a file:` | |
} | |
// the file data | |
const content = 'test1,test2\r\ntrue,false\r\nyes,no' | |
// the file content type | |
const contentType = 'text/csv' | |
await sendWebexFile({ | |
filename:'test.csv', | |
fileMetaName: 'files', | |
contentType, | |
content, | |
metadata | |
}) | |
// done | |
console.log('successfully sent file!') | |
} catch (e) { | |
console.log('error sending file:', e.message) | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment