.then(res => { // SailsJS returnes an array of items in JSON format const aclRules = res.body; // Find the same rule as given from iteration const aclRuleExists = _.find(aclRules, (r) => { return r.id === rule.id; }); // Check if ACL rule actually exists if (aclRuleExists) { // If ACL Rule aleady exists, only update it got.put(`${url}${apiPath}/${rule.id}`, { auth, json: true, body: data }) .then((res1) => { return res1; }) .catch((err) => { return err; }); } else { // If ACL Rule does not exist on remote, then POST it got.post(`${url}${apiPath}`, { auth, json: true, body: data }) .then((res1) => { return res1; }) .catch((err) => { return err; }); } })
function trackEvent (category, action, label, value, cb) { const data = { // API Version. v: '1', // Tracking ID / Property ID. tid: GA_TRACKING_ID, // Anonymous Client Identifier. Ideally, this should be a UUID that // is associated with particular user, device, or browser instance. cid: '555', // Event hit type. t: 'event', // Event category. ec: category, // Event action. ea: action, // Event label. el: label, // Event value. ev: value }; return got.post('http://www.google-analytics.com/collect', { body: data }); }
.map(label => { console.log(` ${label.name}`); if (!LABEL_URL_TO) return; return got.post(LABEL_URL_TO, { json: true, query: { access_token: GITHUB_ACCESS_TOKEN }, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ color: label.color, name: label.name }) }) .catch(err => { if (err.response.body.errors[0].code === 'already_exists') { // Label already exists. Good. return; } console.error(err.message); if (err.response.body.message) { console.error(err.response.body.message); } console.error('Failed!'); process.exit(1); }); })
rulesMap = _.map(rules, (rule) => { // Get data to be sent to EMQ-REST-API const data = { proxyId: rule.proxyId, id: rule.id, allow: rule.allow, access: rule.access, topic: rule.topic, }; // Append ACL type & value data[rule.fromType] = rule.fromValue; // Send POST request to EMQ-REST-API // Append emq-acl path to URL return got.post(`${url}${apiPath}`, { auth, json: true, body: data, }) .then(res => { return res; }) .catch(err => { return err; }); });
suite.tests['#post /metrics-errors - returns 400 with invalid frames'] = function () { return got.post(serverUrl + '/metrics-errors?sentry_version=4', { body: INVALID_METRICS_ERROR_OVEWRITE_SLICE_METHOD, headers: { 'Content-Type': 'application/json' } }).then(assert.fail, (res) => { assert.equal(res.statusCode, 400); }); };
suite.tests['#post /metrics-errors - returns 400 with invalid body'] = function () { return got.post(serverUrl + '/metrics-errors?sentry_version=4', { body: JSON.stringify({}), headers: { 'Content-Type': 'application/json' } }).then(assert.fail, (res) => { assert.equal(res.statusCode, 400); }); };
return function () { return got.post(serverUrl + '/metrics-errors' + (query || ''), { body: JSON.stringify(metricsError), headers: { 'Content-Type': 'application/json' } }) .then((res) => { assert.equal(res.statusCode, 200); }); };
const getGuestToken = async (url = '', opts = {}) => { const { body } = await got.post('https://api.twitter.com/1.1/guest/activate.json', { headers: { Authorization: TWITTER_BEARER_TOKEN }, json: true, timeout: TOKEN_TIMEOUT / 2, retry: 0, agent, ...opts }) return get(body, 'guest_token') }
/** * Add a deployment and trigger an additional round of testing for one of the sites in your account/team. A note is also automatically added to your graphs. * @description POST https://api.speedcurve.com/v1/deploy * @param {Number} siteId: The ID of the site you’d like to trigger a round of testing on. If no site_id then the deployment is added to the first site in the account/team. * @param {String} note: Short URL encoded note to display globally across all graphs for the main site. (Max: 255 characters). * @param {String} detail: Optional URL encoded note detail to display if people want more context. * @returns {Promise} promise */ addDeploy(siteId, note, detail) { const siteIdKey = 'site_id'; const options = Object.assign({}, this.options, { body: { [siteIdKey]: siteId, note, detail } }); return request.post(`${API_ENDPOINT}/deploys`, options); }
_call(dataStr) { return got .post(this._hostPort, { encoding: this._encoding, headers: { 'Content-Type': 'application/json' }, body: dataStr }) .then(res => { return res.body; }); }
fetchToken() { const { clientId, clientSecret, refreshToken } = this; return got.post(refreshTokenURI, { body: { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: 'refresh_token' }, json: true }).then(this._extractBody).then(({ access_token }) => access_token); }
/** * Add a note to one of the sites within your account/team. * @description POST https://api.speedcurve.com/v1/notes * @param {String} timestamp: Either a UTC Unix Timestamp or “now”. Options: (now, unix timestamp). * @param {Number} siteId: ID of site to add note to. If no ID provided then note is added to the first site in the account/team. * @param {String} note: Short URL encoded note to display globally across all graphs for the main site. (Max: 255 characters). * @param {String} detail: Optional note detail to display if people want more context. * @returns {Promise} promise */ addNote(timestamp = 'now', siteId, note, detail) { const siteIdKey = 'site_id'; const options = Object.assign({}, this.options, { body: { timestamp, [siteIdKey]: siteId, note, detail } }); return request.post(`${API_ENDPOINT}/notes`, options); }
hydratePlayable(ids, territory) { if (!this.user) { throw new Error('Must be logged in. See login()'); } return got.post(`https://baboom.com/api/catalogue/playables/hydrate?territory=${territory}`, { json: true, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(Array.isArray(ids) ? ids : [ids]) }) .then(_handleRes); }
function upload (fileStream, cb) { const config = new Conf() const form = new FormData() form.append('file', fileStream) const headers = { 'X-API-KEY': config.get('apiKey'), 'user-agent': `${pkg.name}/${pkg.version}` } return got.post(config.get('url'), { headers: form.getHeaders(headers), body: form }) }
botmon.reply(evt.message.text).then(msg => { msg = { text: msg }; got.post('https://graph.facebook.com/v2.6/me/messages', { json: true, headers: { 'Content-type': 'application/json' }, query: { access_token: process.env.FB_ACCESS_TOKEN }, body: JSON.stringify({ recipient: { id: sender }, message: msg, }) }).catch(err => { console.error(err.response.body); }); });
const fetchPoUrl = ({ project, language }, { token }) => got.post(`${API_URL}/projects/export`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: qs.stringify({ api_token: token, id: project, language, type: 'po', }), }) .then(res => { const { response, result } = JSON.parse(res.body); return response.status === 'success' ? result.url : null; });
return __awaiter(this, void 0, void 0, function* () { // const connection = await MongoClient.connect( // uri, // { useNewUrlParser: true } // ); // const db = connection.db(options.database); const res = yield got.post("https://jmdict.denshajisho.com", { json: true, body: { query: `{ searchEntries(key: "train", first: 1) { edges { node { id } } } }` } }); console.log(res.body); const results = {}; var lineReader = readline_1.createInterface({ input: require('fs').createReadStream('data/examples.utf.example.txt'), }); let i = 0; lineReader.on('line', (line) => __awaiter(this, void 0, void 0, function* () { yield testPromise(); console.log(i++); console.log(line); // const line = decoder.write(chunk); // const [sentence, japaneseDetails] = line.split("B:"); // const [japanese, englishRaw] = sentence.split("\t"); // const english = englishRaw.split("\#")[0]; // const words = japaneseDetails.split("\ ").map((word: string) => { // console.log(`Matches for word ${word}`); // let hiragana, sentenceForm, senseIndex; // // strip the word // word = word.replace(/\((\S+)\)/, (match: string, capture) => {hiragana = capture; return ""}); // word = word.replace(/\{(\S+)\}/, (match: string, capture) => {sentenceForm = capture; return ""}); // word = word.replace(/\[(\S+)\]/, (match: string, capture) => {senseIndex = capture; return ""}); // word = word.replace("~", ""); // word = word.trim(); // console.log(`word: ${word}: ${japanese} | ${english}`); // results[word] ? results[word].push({japanese, english, japaneseDetails}) : results[word] = [{japanese, english, japaneseDetails}]; // }); })); lineReader.on("error", console.log); });
module.exports.verify = async function (private_key, user_ip, response) { let data = { secret: private_key, remoteip: user_ip, response }; // Immediately reply 'wrong captcha' // - if user not filled captcha field if (_.isEmpty(response)) { return false; } // If any param is empty - fail immediately, don't make request to server if (_.values(data).some(el => _.isEmpty(el))) { throw new Error('ReCaptcha: Bad verify params'); } let res; try { res = await got.post( 'https://www.google.com/recaptcha/api/siteverify', { body: data, form: true, retry: 1 } ); } catch (err) { throw new Error('reCaptcha server request failed.'); } if (res.statusCode !== 200) { throw new Error('reCaptcha server request failed.'); } let result; try { result = JSON.parse(res.body); } catch (__) { throw new Error(`reCaptcha server returned bad response: ${res.body}`); } return result.success; };
login(email, password, remember_me = false) { return got.post('https://baboom.com/auth/login', { json: true, headers: { 'X-BB-S': '1', 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password: pwdHash(password), remember_me }) }) .then(_handleRes) .then(res => { // store user this.user = res.user; return res.user; }); }
/** * Reports errors to Sentry * @param {Object} query * Query from the error request. * @param {String} body * Body of the error request. */ function reportError(query, body) { if (! query || ! body || ! _.isObject(query) || ! _.isObject(body)) { logger.error('reportError bad query or body', { body: body, query: query }); return; } if (sentryConfig && sentryConfig.endpoint && API_KEY && API_SECRET) { // set API_KEY and API_SECRET using the server query['sentry_key'] = API_KEY; query['sentry_secret'] = API_SECRET; body = setExtraSentryData(body); const newQuery = querystring.stringify(query); got.post(sentryConfig.endpoint + '?' + newQuery, { body: JSON.stringify(body) }).catch(function (err) { logger.error(err, body); }); } }
module.exports = co.wrap(function* post(filePath) { // if filePath is url // download it and temp-write it to a file if (isUrl(filePath)) { filePath = yield download(filePath).catch(err => console.log(err.stack)); } // output image in terminal yield imgcat(filePath).catch(() => {/* do nothing */}); const file = fs.createReadStream(path.resolve(filePath)); // start spinner uploadSpin.start(); // create form form.append('smfile', file); form.append('ssl', 'true'); // post form const data = yield got.post('https://sm.ms/api/upload', { headers: form.getHeaders(), body: form, json: true }).then(res => res.body); // stop spinner uploadSpin.stop(); // exit when error occurs if (data.code !== 'success') { console.log(data.msg.red); process.exit(1); } // return result return data.data; });
export const uploadTranslations = (pot, options, credentials = {}) => { const { project, sourceLanguage } = options; const potStream = stringToStream(pot); // Prevent the POEditor API from complaining about file extension potStream.path = `${project}.pot`; const form = new FormData(); form.append('api_token', credentials.token); form.append('id', project); form.append('updating', 'terms_translations'); form.append('language', sourceLanguage); form.append('file', potStream); form.append('sync_terms', '1'); const url = `${API_URL}/projects/upload`; const requestOptions = { headers: form.getHeaders(), body: form, }; return got.post(url, requestOptions); };
(async() => { let body = ''; try { const res = await got.post('http://overpass-api.de/api/interpreter', { body: `data=${encodeURIComponent(` /* This has been generated by the overpass-turbo wizard. The original search was: “"bus stop" in Singapore” */ [out:json][timeout:25]; // fetch area “Singapore” to search in area(3601769123)->.searchArea; // gather results ( // query part for: “"bus stop"” node["highway"="bus_stop"](area.searchArea); ); // print results out body; >; out skel qt; `)}` }); body = res.body; } catch (e) { console.error(e); } const filePath = 'data/3/stops.osm.json'; fs.writeFileSync(filePath, body); console.log(`Generated ${filePath}`); })();
return eventualToken.then(token => { return got.post(publishURI(extensionId, target), { headers: this._headers(token), json: true }).then(this._extractBody); });
export function post (url, data) { const opts = getOpts() opts.body = JSON.stringify(data) return request.post(url, opts) }
tremblingCreatureOrHaveITheRight (user) { return _.includes(config.telegramAllowedUsers, user); }, sendMessage (lastUpdate, text) { let opts = { method: 'POST', encoding: 'utf8', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({chat_id: lastUpdate.from.id, text: text}) } got.post('https://api.telegram.org/bot' + config.telegramBotToken + '/sendMessage', { body: {chat_id: lastUpdate.from.id, text: text} }) .catch(err => { console.error(err); console.error(err.response && err.response.body); return console.error('failed to send telegram message:', err); }); // request.post({ // url: 'https://api.telegram.org/bot' + config.telegramBotToken + '/sendMessage', // form: {chat_id: lastUpdate.from.id, text: text} // }, // function(err, httpResponse, body) { // if (err) { // return console.error('failed to send telegram message:', err); // }
function dbNotify () { return got.post('http://localhost:3030/dbChange') .catch(e => console.error('Error: lamassu-server not responding')) }
process.exit(-1); } var gitCommitHash = gitCommitRet.stdout.trim(); console.log("Git commit: "+gitCommitHash); console.log('Calling Travis...'); got.post("https://api.travis-ci.org/repo/"+encodeURIComponent(targetRepo)+"/requests", { headers: { "Content-Type": "application/json", "Accept": "application/json", "Travis-API-Version": "3", "Authorization": "token "+process.env.TRAVIS_API_TOKEN }, body: JSON.stringify({ request: { message: "Trigger build at "+targetRepo+" commit: "+gitCommitHash, branch: 'master' } }) }) .then(function(){ console.log("Triggered build of "+targetRepo); }) .catch(function(err){ console.error(err); process.exit(-1); });