export-stats-update

node v10.24.1
version: 5.0.0
endpointsharetweet
This is called by Slack, adds a document to the database and returns a message for Slack.
const moment = require('moment') const qs = require('querystring') const mongoose = require('mongoose') mongoose.Promise = require('bluebird') const dbUser = process.env.EXPORT_STATS_MONGO_USER const dbPwd = process.env.EXPORT_STATS_MONGO_PWD const dbHost = process.env.EXPORT_STATS_MONGO_HOST const dbPort = process.env.EXPORT_STATS_MONGO_PORT const dbDb = process.env.EXPORT_STATS_MONGO_DB exports.endpoint = (request, response) => { // only accept requests for the actual endpoint if (request.url !== '/') { response.statusCode = 404 response.end(`'${request.url}' not handled.`) // only accept POST requests } else if (request.method !== 'POST') { response.statusCode = 405 response.end(`Unsupported method '${request.method}', use 'POST'.`) return } mongoose.openUri(`mongodb://${dbUser}:${dbPwd}@${dbHost}:${dbPort}/${dbDb}`, (err) => { console.log(`problem connecting to database: ${err}`) }) const db = mongoose.connection // db.on('error', console.error.bind(console, 'connection error:')) try { // make sure we record the appropriate day for the export const today = moment() const now = moment() let date = today.clone().subtract(1, 'd') if (today.day() <= 1 || today.day() > 5) { date = today.clone().day(-2) } const _start = date.clone().utc().startOf('day') const _end = date.clone().utc().endOf('day') // once the connection has been established ... db.once('open', async () => { const Schema = mongoose.Schema const exportSchema = new Schema({ date: { type: Date, default: Date.now }, exportSuccessful: Boolean, month: Number, week: Number, weekDay: String }) const Export = mongoose.model('Export', exportSchema) const exArr = await Export.find({date: { $gte: _start, $lte: _end }}) const existsAlready = exArr.length // console.log(`existsAlready: ${existsAlready}, start: ${_start}, end: ${_end}`) // get the data from the POST body let body = '' request.on('data', (data) => { console.log('collecting data from request ...') body += data if (body.length > 1e6) { request.connection.destroy() db.close() } }) db.close() request.connection.destroy() response.end(`Got here. ${body}`) return request.on('end', () => { const content = qs.parse(body) // const payload = JSON.parse(content.payload) const payload = {"user": {"id": "TESTUSER"}, "actions": [{"value": "ok"}]} // console.log(`PAYLOAD: ${JSON.stringify(payload)}`) const exportSuccessful = (payload.actions[0].value === 'ok') const userId = payload.user.id const responseMsg = exportSuccessful ? `Great! :+1: Thanks a lot` : `Hmmm, this smells like a PDCA! :wink: Thanks anyway` const responseDate = (now.day() <= 1 || now.day() > 5) ? 'Friday' : 'yesterday' const resMsg = `${responseMsg} <@${userId}>, ${responseDate}'s export has been successfully recorded. <https://jfix.github.io/export-stats/|Find out more>.` const errMsg = `Really sorry but for some weird reason I couldn't save the export. Please see an administrator with this info:` if (existsAlready) { // don't save document if there is already one with the same date console.log(`Not adding document to database (already one with ${date.toDate()} in the db).`) response.end(resMsg) } else { console.log(`About to add document to database ...`) // prepare the data to save in the database const anExport = new Export({ date: date.toDate(), exportSuccessful: exportSuccessful, month: date.month(), week: date.week(), weekDay: date.format('ddd') }) anExport.save((err, exp) => { if (err) { console.log(`Error while saving: ${JSON.stringify(err)}`) response.statusCode = 500 response.end(`${errMsg} ${JSON.stringify(err)}`) } else { console.log(`Successfully saved document in database.`) response.end(resMsg) } }) } db.close() console.log('Finished interaction, closed database. Good-bye!') }) // request handling }) // db open } catch (e) { db.close() const msg = `UNHANDLED ERROR :( -> ${JSON.stringify(e)}` response.statusCode = 500 response.end(msg) console.log(msg) } }
Loading…

no comments

    sign in to comment