Skip to content

Instantly share code, notes, and snippets.

@remydavid
Last active December 4, 2018 09:18
Show Gist options
  • Save remydavid/8bd0387c3f251bd834fb442d405fc829 to your computer and use it in GitHub Desktop.
Save remydavid/8bd0387c3f251bd834fb442d405fc829 to your computer and use it in GitHub Desktop.
const winston = require('winston');
const monkey = require('./data-studio-monkey-refresher');
const express = require('express');
(async () => {
const Logger = winston.Logger;
const Console = winston.transports.Console;
// Imports the Google Cloud client library for Winston
const LoggingWinston = require('@google-cloud/logging-winston').LoggingWinston;
// Creates a Winston Stackdriver Logging client
const loggingWinston = new LoggingWinston({
prefix: 'monkey',
serviceContext: {
service: 'data-studio-monkey-refresher',
version: 'dev'
}
});
// Create a Winston logger that streams to Stackdriver Logging
const logger = winston.createLogger({
level: 'info', // log at 'info' and above
transports: [
// Log to the console
new Console(),
// And log to Stackdriver Logging
loggingWinston
]
});
let browser;
let server;
const app = express();
process.on('exit', async () => {
logger.info('Process exit, shutdown app...');
try{
server.close();
}catch(err){
logger.warn('Could not stop express server ' + err.message);
}
if(browser != null){
try{
await browser.close();
}catch(err){
logger.error('Could not stop Puppeteer ' + err.message);
}
}else{
logger.warn('Puppeteer not running, shuting down');
}
});
process.on('uncaughtException', (err) => {
logger.error('uncaugthException' + err.message);
});
process.on('unhandledRejection', (reason, p) => {
logger.error('Unhandled Rejection at:' + p + ' reason: ' + reason);
});
app.get('/', (req, res) => {
logger.info('Refresh triggered');
if(browser != null){
monkey.refreshReports(logger,browser)
.then( () => res.status(200).send('Pages refreshed').end())
.catch( (err) => res.status(500).send('Pages could not be refreshed').end());
}else{
logger.error('Puppeteer not running');
res.status(500).send('Puppeteer not running').end()
}
});
async function init () {
await monkey.init()
.then( (b) => { browser = b; logger.info('Puppeteer started'); } )
.catch( (err) => {
logger.error('Could not start puppeteer '+ err);
});
if(browser != null){
// Start the server
const PORT = process.env.PORT || 8080;
server = app.listen(PORT, async () => {
logger.info(`App listening on port ${PORT}`);
});
}
}
init();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment