Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'koa-compress' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
import serverConfig from '../../webpack/ssr/server';
const DEBUG = !(['production', 'development', 'staging'].includes(process.env.NODE_ENV));
const DEVELOPMENT = (['development', 'staging'].includes(process.env.NODE_ENV));
// Redefined publicPath and outputPath instead of import clientConfig to solve
// prod importation problems
const publicPath = DEBUG ? config.apps.frontend.baseName.debug : config.apps.frontend.baseName.production;
const outputPath = path.resolve(__dirname, '../../build/ssr/client');
const app = new Koa();
app.use(helmet());
app.use(cookie());
app.use(compress());
// let's encrypt config
const resolve = p => path.resolve(__dirname, p);
app.use(mount('/.well-known', serve(resolve('../../.well-known'))));
// UNIVERSAL HMR + STATS HANDLING GOODNESS:
if (DEVELOPMENT) {
const multiCompiler = webpack([clientConfig, serverConfig]);
const clientCompiler = multiCompiler.compilers[0];
// First we fire up Webpack an pass in the configuration we
// created
let bundleStart = null;
// We give notice in the terminal when it starts bundling and
// set the time it started
clientCompiler.plugin('compile', () => {
Raven.config(nullthrows(process.env.SNACK_SENTRY_DSN), {
release: process.env.NODE_ENV === 'production' ? nullthrows(process.env.APP_VERSION) : null,
captureUnhandledRejections: true,
shouldSendCallback() {
return process.env.NODE_ENV === 'production';
},
}).install();
}
const app = new Koa();
if (process.env.COMPRESS_ASSETS === 'true') {
// Enable gzip compression conditionally, for development
// This makes it easier to test how big bundles will be in production
app.use(compress());
}
app.use(sw());
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
app.use(mount('/dist', serve(path.join(__dirname, '..', '..', 'dist'))));
} else {
// Use webpack dev middleware in development
const webpack = require('webpack');
const dev = require('webpack-dev-middleware');
const config = require('../../webpack.config');
const compiler = webpack(config);
const middleware = dev(compiler, {
publicPath: '/dist/',
stats: 'minimal',
export async function createServer() {
logger.debug('Creating server...')
const app = new Koa()
// Container is configured with our services and whatnot.
const container = (app.container = configureContainer())
app
// Top middleware is the error handler.
.use(errorHandler)
// Compress all responses.
.use(compress())
// Adds ctx.ok(), ctx.notFound(), etc..
.use(respond())
// Handles CORS.
.use(cors())
// Parses request bodies.
.use(bodyParser())
// Creates an Awilix scope per request. Check out the awilix-koa
// docs for details: https://github.com/jeffijoe/awilix-koa
.use(scopePerRequest(container))
// Create a middleware to add request-specific data to the scope.
.use(registerContext)
// Load routes (API "controllers")
.use(loadControllers('../routes/*.js', { cwd: __dirname }))
// Default handler when nothing stopped the chain.
.use(notFoundHandler)
return app.use(generatePrometheusMiddleware(router, {
ignore: [/^\/repository/]
}))
.use(generateProblemMiddleware({
exposableErrorTypes: [
CHECK_ERROR_TYPE,
GITHUB_ERROR_TYPE,
REPO_ERROR_TYPE
]
}))
.use(morgan(morganFormat, {skip: morganSkip}))
.use(convert(session({store: store})))
.use(bodyParser())
.use(passport.initialize())
.use(passport.session())
.use(compress())
.use(router.routes())
.use(router.allowedMethods())
.use(conditional())
.use(etag())
.use(serve(
nconf.get('STATIC_DIR'), {
index: 'none',
maxage: 1.7 * 10 ** 8 // ~ 2 days
}))
.use(ensureModeMiddleware)
.use(renderStatic)
}
const origin = ctx.get('origin');
if (!!origin.length && config.apps.api.allowedOrigins.indexOf(origin) === -1) {
return false;
}
return origin;
},
}));
// DB connection
app.use(connectToDbMiddleware(pool.connect, appLogger, config.apps.api.db));
if (env !== 'development') {
// gzip compression
app.use(compress());
}
app.use(koaBodyParser());
app.use(koaMount('/api', api));
app.use(koaMount('/admin', admin));
if (!module.parent || module.parent.filename.indexOf('api/index.js') !== -1) {
app.listen(port);
appLogger.info(`API server listening on port ${port}`);
appLogger.info('Press CTRL+C to stop server');
}
export default app;
import logger from 'koa-logger';
import mount from 'koa-mount';
import enforceHttps from 'koa-sslify';
import Koa from 'koa';
import bugsnag from 'bugsnag';
import onerror from 'koa-onerror';
import updates from './utils/updates';
import auth from './auth';
import api from './api';
import emails from './emails';
import routes from './routes';
const app = new Koa();
app.use(compress());
if (process.env.NODE_ENV === 'development') {
/* eslint-disable global-require */
const convert = require('koa-convert');
const webpack = require('webpack');
const devMiddleware = require('koa-webpack-dev-middleware');
const hotMiddleware = require('koa-webpack-hot-middleware');
const config = require('../webpack.config.dev');
const compile = webpack(config);
/* eslint-enable global-require */
app.use(
convert(
devMiddleware(compile, {
// display no info to console (only warnings and errors)
noInfo: true,
ratelimit({
db: redis,
duration: 60000,
errorMessage:
"Please stop hitting us so hard. Please deploy your own instance of the API",
id: ctx => ctx.get("X-Real-IP"),
headers: {
remaining: "Rate-Limit-Remaining",
reset: "Rate-Limit-Reset",
total: "Rate-Limit-Total"
},
max: 50
})
);
}
app.use(compress());
app.use(cors());
app.use(mount("/api", api));
if (process.env.NODE_ENV === "development") {
app.use(logger());
}
export default app;
import Koa from 'koa'
import json from 'koa-json'
import bodyParser from 'koa-bodyparser'
import logger from 'koa-logger'
import session from 'koa-session'
import compress from 'koa-compress'
import convert from 'koa-convert'
const app = new Koa()
app.keys = ['this is a fucking secret']
app.use(convert(session(app)))
app.use(compress())
app.use(bodyParser())
app.use(json())
app.use(logger())
export default app
export default function createServer({apps=[], heapId}) {
const server = koa();
apps.forEach(app => server.use(serve(`${app}/public`)));
server.use(serve(`${__dirname}/../public`));
server.use(logger());
server.use(compress());
server.use(htmlMinifier({collapseWhitespace: true}));
server.use(panels({heapId, prerender: !!process.env.PRERENDER}));
return server;
}