1.1.1 • Published 2 years ago

@danielhuisman/koa-base v1.1.1

Weekly downloads
16
License
MIT
Repository
github
Last release
2 years ago

koa-base

Koa server with basic middleware.

Middleware

Installation

yarn add @danielhuisman/koa-base

Usage

import path from 'path';
import {createServer, startServer, logger} from '@danielhuisman/koa-base';
import Router from 'koa-router';

const config = {
    port: 5000,

    session: {
        secret: 'sessionSecret'
    },

    static: {
        serve: process.env.STATIC_SERVE !== 'false',
        path: path.join(__dirname, '..', 'static')
    }
};

(async () => {
    logger.info('Starting application...');

    // Initialize server
    const {server, app} = createServer(config);

    // Initialize router
    const router = new Router();

    // Index route
    router.get('/', async (ctx) => {
        return ctx.success({
            message: 'Hello World!'
        }, 200);
    });

    // Add router
    app.use(router.routes());
    app.use(router.allowedMethods());

    // Handle unknown routes
    app.use(async (ctx, next) => {
        ctx.error(404, 'Not found');
        await next();
    });

    // Start server
    await startServer(config, server);

    logger.info('Started application.');
})();