How to use koa-compose - 10 common examples

To help you get started, we’ve selected a few koa-compose 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 garbin / koapi / src / router.es View on Github external
read(){
    let {middlewares, options} = parse_args(arguments, {
      joins: [],
      sortable: [],
      searchable: [],
      filterable: [],
      pagination:undefined,
      fetch: {},
      fetchItem: {},
    });
    let {collection, options:{id}, pattern} = this;
    this.methods.read = true;
    // read list
    this.get(pattern.root,
             convert(paginate(options.pagination)),
             compose(middlewares),
             async (ctx) => {
               let query = ctx.state.query || collection(ctx).model.forge();
               if (collection(ctx).relatedData) {
                 query = query.where({[collection(ctx).relatedData.key('foreignKey')]:collection(ctx).relatedData.parentId})
               }
               if (options.joins) {
                 options.joins.forEach(relation => query.join(relation));
               }
               if (options.sortable) {
                 let order_by = _.get(ctx, 'request.query.sort', _.first(options.sortable));
                 if (_.includes(options.sortable, _.trimStart(order_by, '-'))) {
                   query = query.orderBy(order_by, order_by[0] == '-' ? 'DESC' : 'ASC');
                 }
               }
               if (options.filterable) {
                 let filters = options.filterable.map(filter => {
github rusty1s / koa2-rest-api / server / middleware / index.js View on Github external
export default function middleware() {
  return compose([
    logger(),
    helmet(), // reset HTTP headers (e.g. remove x-powered-by)
    convert(cors()),
    convert(bodyParser()),
    convert(session()),
  ]);
}
github vtex / node-vtex-api / src / HttpClient / HttpClient.ts View on Github external
... tenant ? {[TENANT_HEADER]: formatTenantHeaderValue(tenant)} : null,
      ... binding ? {[BINDING_HEADER]: formatBindingHeaderValue(binding)} : null,
      ... locale ? {[LOCALE_HEADER]: locale} : null,
      ... operationId ? {'x-vtex-operation-id': operationId} : null,
      ... product ? {[PRODUCT_HEADER]: product} : null,
      ... segmentToken ? {[SEGMENT_HEADER]: segmentToken} : null,
      ... sessionToken ? {[SESSION_HEADER]: sessionToken} : null,
    }

    if (authType && authToken) {
      headers['Authorization'] = `${authType} ${authToken}` // tslint:disable-line
    }

    const memoizedCache = new Map>()

    this.runMiddlewares = compose([...opts.middlewares || [],
      defaultsMiddleware(baseURL, headers, params, timeout, retries, verbose),
      metricsMiddleware({metrics, serverTiming, name}),
      memoizationMiddleware({memoizedCache}),
      ...recorder ? [recorderMiddleware(recorder)] : [],
      cancellationToken(cancellation),
      singleFlightMiddleware,
      acceptNotFoundMiddleware,
      ...memoryCache ? [cacheMiddleware({type: CacheType.Memory, storage: memoryCache})] : [],
      ...diskCache ? [cacheMiddleware({type: CacheType.Disk, storage: diskCache})] : [],
      notFoundFallbackMiddleware,
      routerCacheMiddleware,
      requestMiddleware(limit),
    ])
  }
github neo-one-suite / neo-one / packages / neo-one-server / src / middleware / rpc.ts View on Github external
// error: {},

      // tslint:disable-next-line no-var-before-return
      return result;
    } catch (error) {
      return {
        type: 'error',
        message: error.message,
      };
    }
  };

  return {
    name: 'rpc',
    path: '/rpc',
    middleware: compose([
      koaCompress(),
      bodyParser(),
      async (ctx: Context): Promise => {
        if (!ctx.is('application/json')) {
          return ctx.throw(415);
        }

        // tslint:disable-next-line no-any
        const { body } = ctx.request as any;
        const logger = getLogger(ctx);
        const result = await handleRequestSafe(logger, body);

        ctx.status = 200;
        ctx.body = result;
      },
    ]),
github m3-moretv / smogger / src / components / router / index.js View on Github external
) => (paths: PathItem): Application => {
  const app = new Koa();

  const serverMiddlewares = koaCompose([
    ...createRouteMiddlewares(paths),
    setRequestStateMiddleware,
    cacheMiddleware,
    createProcessingMiddleware(middlewares)
  ]);

  app.use(serverMiddlewares);
  app.listen(port);

  console.log(`Mock server working on :${port}`);
  return app;
};
github ddellamico / koa-rest-api-es6 / src / api / auth / oauth2.js View on Github external
export function token() {
  return compose([
    passport.authenticate(['basic', 'clientPassword'], { session: false }),
    server.token(),
    server.errorHandler()
  ]);
}
github famanoder / eryue / src / lib / default-middlewares.js View on Github external
const {status, body} = $body;
    cx.status = status;
    cx.body = body;
  }
}

const middlewares = [
  catchError,
  compress(),
  bodyparser(),
  loadConfig(withStatic),
  loadConfig(withFavicon),
  loadRoutes
];

export default compose(middlewares);
github avgjs / avg-core / src / core / core.js View on Github external
post(name, context, next) {
    const middlewares = this.middlewares[name];

    if (middlewares) {
      return compose(middlewares)(context || {}, next);
    }

    return Promise.resolve();
  }
github FreeFeed / freefeed-server / app / controllers / api / v2 / AppTokensController.js View on Github external
monitored('app-tokens.update'),
  async (ctx) => {
    const { state: { user }, request: { body: { title } } } = ctx;
    const token = await dbAdapter.getAppTokenById(ctx.params.tokenId);

    if (!token || token.userId !== user.id || !token.isActive) {
      throw new NotFoundException('Token not found');
    }

    await token.setTitle(title);

    ctx.body = { token: serializeAppToken(token) };
  },
]);

export const list = compose([
  authRequired(),
  monitored('app-tokens.update'),
  async (ctx) => {
    const { state: { user } } = ctx;

    const tokens = await dbAdapter.listActiveAppTokens(user.id);

    ctx.body = { tokens: tokens.map(serializeAppToken) };
  },
]);

export const scopes = (ctx) => (ctx.body = { scopes: appTokensScopes });

function serializeAppToken(token) {
  return pick(token, [
    'id',
github superalsrk / koa2-boilerplate / src / routes / index.js View on Github external
export default function routes() {
    return compose(
        [
            router.routes(),
            router.allowedMethods()
        ]
    )
}

koa-compose

compose Koa middleware

MIT
Latest version published 7 years ago

Package Health Score

77 / 100
Full package analysis

Popular koa-compose functions