How to use the koa-mount function in koa-mount

To help you get started, we’ve selected a few koa-mount examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github outline / outline / server / app.js View on Github external
bugsnag.register(process.env.BUGSNAG_KEY, {
      filters: ['authorization'],
    });
    app.on('error', (error, ctx) => {
      // we don't need to report every time a request stops to the bug tracker
      if (error.code === 'EPIPE' || error.code === 'ECONNRESET') {
        console.warn('Connection error', { error });
      } else {
        bugsnag.koaHandler(error, ctx);
      }
    });
  }
}

app.use(mount('/auth', auth));
app.use(mount('/api', api));

app.use(helmet());
app.use(
  contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: [
        "'self'",
        "'unsafe-inline'",
        "'unsafe-eval'",
        'gist.github.com',
        'www.google-analytics.com',
        'd2wy8f7a9ursnm.cloudfront.net',
      ],
      styleSrc: ["'self'", "'unsafe-inline'", 'github.githubassets.com'],
      imgSrc: ['*', 'data:', 'blob:'],
github freedomexio / rocketx-condenser / server / server.js View on Github external
);
// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const webpack_dev_port = process.env.PORT
        ? parseInt(process.env.PORT) + 1
        : 8081;
    const proxyhost = 'http://0.0.0.0:' + webpack_dev_port;
    console.log('proxying to webpack dev server at ' + proxyhost);
    const proxy = require('koa-proxy')({
            host: proxyhost,
            map: filePath => 'assets/' + filePath
});
    app.use(mount('/assets', proxy));
} else {
    app.use(
        mount(
            '/assets',
            staticCache(path.join(__dirname, '../dist'), cacheOpts)
        )
    );
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function*() {
        yield appRender(this);
        // if (app_router.dbStatus.ok) recordWebEvent(this, 'page_load');
        const bot = this.state.isBot;
        if (bot) {
            console.log(
                `  --> ${this.method} ${this.originalUrl} ${this.status} (BOT '${bot}')`
            );
github gtg092x / another-ssr-boilerplate / src / api / index.js View on Github external
})

router.get('/about', async (ctx) => {
  await new Promise(resolve => setTimeout(resolve, 500))
  ctx.body = {
    content: 'This is our about section. It took 500 milliseconds to load.',
  }
})

const middleware = compose([
  router.allowedMethods(),
  router.routes(),
])

// this would make all routes have `/api` in front of them (e.g. /api/home)
export default mount('/api', middleware)
github Someguy123 / understeem / server / server.js View on Github external
// useGeneralApi(app);

app.use(favicon(path.join(__dirname, '../app/assets/images/favicons/favicon.ico')));
app.use(isBot());
app.use(mount('/favicons', staticCache(path.join(__dirname, '../app/assets/images/favicons'), cacheOpts)));
app.use(mount('/images', staticCache(path.join(__dirname, '../app/assets/images'), cacheOpts)));
// Proxy asset folder to webpack development server in development mode
if (env === 'development') {
    const PORT = parseInt(process.env.PORT, 10) + 1 || 3001;
    const proxy = require('koa-proxy')({
        host: 'http://0.0.0.0:' + PORT,
        map: (filePath) => 'assets/' + filePath
    });
    app.use(mount('/assets', proxy));
} else {
    app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)));
}

if (env !== 'test') {
    const appRender = require('./app_render');
    app.use(function* () {
        this.first_visit = false;
        this.last_visit = this.session.last_visit;
        this.session.last_visit = (new Date()).getTime() / 1000 | 0;
        if (!this.session.uid) {
            this.session.uid = Math.random().toString(36).slice(2);
            this.first_visit = true;
            this.session.new_visit = true;
        } else {
            this.session.new_visit = this.session.last_visit - this.last_visit > 1800;
        }
        yield appRender(this);
github expo / snack-web / src / server / index.js View on Github external
},
  }).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',
  });

  app.use(async (ctx, next) => {
    await middleware(
      ctx.req,
      {
github roastlechon / generator-koa2-rest / src / app / templates / src / config / routes.js View on Github external
export default function configRoutes(app) {
  app.use(mount('/', root.routes()));

  // List Endpoints Here
}
github amazing-gao / koa-oai-router / lib / oai-explorer.js View on Github external
options.apiExplorerPath = `${options.apiExplorerPath}`;
    options.apiExplorerStaticPath = `${options.apiExplorerStaticPath}`;
    options.apiExplorerLink = `${options.apiExplorerLink}`;

    if (!options.apiExplorerVisible) return (ctx, next) => { return next(); };

    debug('render api-explorer', options);
    console.log(`ApiExplorer: http://127.0.0.1:${options.port}${options.apiExplorerPath}`);

    const swaggerUiDist = path.dirname(require.resolve('koa-oai-router-swagger-ui-dist'));

    return compose([
      views(swaggerUiDist, {map: {html: 'mustache'}, renderName: 'renderSwagger'}),
      mount(options.apiExplorerStaticPath, statics(path.dirname(options.apiDoc))),
      mount(options.apiExplorerStaticPath, statics(swaggerUiDist)),
      mount(options.apiExplorerPath, async (ctx, next) => {
        options.apiDoc = path.basename(options.apiDoc);
        await ctx.renderSwagger('index.html', options);
      }),
    ]);
  }
}
github AwesomeLogos / awesome-logos / src / server.ts View on Github external
app.use(async(ctx, next) => {
    try {
        await next();
        const status = ctx.status || 404;
        if (status === 404) {
            ctx.status = 404;
            await ctx.render('404.hbs', { title: '404', h1: '404 - Page not found', url: ctx.req.url });
        }
    } catch (err) {
        ctx.status = 500;
        await ctx.render('500.hbs', { title: 'Server Error', message: err.message });
    }
});

app.use(KoaStatic("static"));
app.use(KoaMount('/logos', KoaStatic("logos")));


app.use(KoaViews(path.join(__dirname, '..', 'views'), {
    map: { hbs: 'handlebars' },
    options: {
        helpers: {
            'addCommas': function (num:number) {
                return num.toLocaleString();
            },
            'equals': function(a:any, b:any, block:any) {
                return a == b ? block.fn() : '';
            },
            'for': function(from:number, to:number, incr:number, block:any) {
                let result = '';
                for (let loop = from; loop < to; loop += incr)
                    result += block.fn(loop);
github lionsharecapital / lionshare-api / app.js View on Github external
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;
github catamphetamine / webpack-react-redux-server-side-render-example / code / common / web server.js View on Github external
result.proxy = (from, to) =>
	{
		if (exists(to))
		{
			web.use(mount(from, koa_proxy({ host: to })))
		}
		else
		{
			to = from
			web.use(koa_proxy({ host: to }))
		}
	}

koa-mount

Mounting middleware for koa

MIT
Latest version published 6 years ago

Package Health Score

62 / 100
Full package analysis

Popular koa-mount functions