Skip to content

Instantly share code, notes, and snippets.

@alonronin
Last active February 24, 2020 17:45
Show Gist options
  • Save alonronin/538f7cbd58a5e8eb346dd5f96d3b0263 to your computer and use it in GitHub Desktop.
Save alonronin/538f7cbd58a5e8eb346dd5f96d3b0263 to your computer and use it in GitHub Desktop.
JS-IL 02/2020
const express = require('express');
const { json, urlencoded } = require('body-parser');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const debug = require('debug');
const compression = require('compression');
const http = require('http');
const camelCase = require('lodash.camelcase');
const Create = context => {
const log = debug(camelCase(context));
const error = log.extend('errors');
const chassis = log.extend('chassis');
chassis('started in %s mode', process.env.NODE_ENV || 'undefined');
const logger = { log, error };
const app = express();
app.enable('trust proxy');
app.use(helmet());
app.use(helmet.noCache());
app.use(morgan('short'));
app.use(cors());
app.use(compression());
app.use(json({ limit: '50mb' }));
app.use(urlencoded({ extended: false }));
const healthCheck = (routes = ['/', '/healthz']) => {
const ok = (req, res) => res.send('ok');
const router = new express.Router();
routes.forEach(route => router.get(route, ok));
return router;
};
const notFoundHandler = (req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
};
const errorHandler = (err, req, res, next) => {
const error = err;
err.status !== 404 && logger.error(err);
res.status(err.status || 500).json({
message: err.message,
error
});
};
const normalizePort = val => {
const port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
const serverStart = app =>
new Promise((resolve, reject) => {
const server = http.createServer(app);
const port = normalizePort(app.get('port') || process.env.PORT || 8080);
server.listen(port);
server.on('error', error => {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
let reason = error;
if (error.code === 'EACCES') reason = `${bind} requires elevated privileges`;
if (error.code === 'EADDRINUSE') reason = `${bind} is already in use`;
reject(reason);
});
server.on('listening', async () => {
const addr = server.address();
const bind =
typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port + ' on ' + addr.address;
resolve(`Listening on ${bind}`);
});
});
process.on('uncaughtException', (err, origin) => {
logger.error('Unhandled Exception at:', origin, 'err:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
return {
app,
express,
healthCheck,
notFoundHandler,
errorHandler,
serverStart,
logger,
context
};
};
module.exports = { Create };
const getCloudRunToken = async service => {
if (process.env.NODE_ENV !== 'production') return;
const url = `http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=${service}`;
const { data: token } = await axios.get(url, {
headers: {
'Metadata-Flavor': 'Google'
}
});
return token;
};
module.exports = getCloudRunToken;
FROM node:12
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# If running Docker >= 1.13.0 use docker run's --init arg to reap zombie processes, otherwise
# uncomment the following lines to have `dumb-init` as PID 1
ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64 /usr/local/bin/dumb-init
RUN chmod +x /usr/local/bin/dumb-init
ENTRYPOINT ["dumb-init", "--"]
WORKDIR /app/
ENV NODE_ENV production
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true
ENV EXECUTABLE_PATH 'google-chrome-unstable'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment