"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const koa_1 = __importDefault(require("koa"));
const apollo_server_koa_1 = require("apollo-server-koa");
const koa_bodyparser_1 = __importDefault(require("koa-bodyparser"));
const koa_jwt_1 = __importDefault(require("koa-jwt"));
// @ts-ignore
const graphql_upload_1 = require("graphql-upload");
const database_1 = require("./initializers/database");
const routes_1 = require("./routes");
const schema_1 = require("./graphql/schema");
const auth_middleware_1 = require("./middlewares/auth-middleware");
const args = require('args');
args.option('port', 'The port on which the app will be running', 3000);
const flags = args.parse(process.argv);
const path = require('path');
const PORT = (process.env.PORT = flags.port);
const SHELL_MODULE_ROOT_DIR = path.join(__dirname, '..');
const UPLOAD_DIR = (process.env.UPLOAD_DIR = path.join(process.cwd(), 'uploads'));
const bodyParserOption = {
    formLimit: '10mb',
    jsonLimit: '10mb',
    textLimit: '10mb'
};
const bootstrap = async () => {
    await database_1.databaseInitializer();
    const app = new koa_1.default();
    app.on('error', (err, ctx) => {
        console.log('error ===>', err);
        /* centralized error handling:
         *   console.log error
         *   write error to log file
         *   save error and request information to database if ctx.request match condition
         *   ...
         */
    });
    /* authentication error handling */
    app.use(async (ctx, next) => {
        return next().catch(err => {
            if (err.status === 401) {
                ctx.status = 401;
                ctx.body = {
                    error: err.originalError ? err.originalError.message : err.message
                };
            }
            else {
                throw err;
            }
        });
    });
    const server = new apollo_server_koa_1.ApolloServer({ schema: schema_1.schema });
    const render = require('koa-ejs');
    render(app, {
        root: path.join(__dirname, '..', 'views'),
        layout: 'template',
        viewExt: 'html',
        cache: false,
        debug: false
    });
    app.use(koa_bodyparser_1.default(bodyParserOption));
    app.use(koa_jwt_1.default({
        secret: '0xD58F835B69D207A76CC5F84a70a1D0d4C79dAC95',
        cookie: 'access_token',
        getToken: auth_middleware_1.getToken
    }).unless({ path: [/^(?!.graphql|.file|.uploads|.authcheck).*$/] })
    /* 위의 path로 시작하는 경우에만, authcheck를 한다. */
    );
    /* jwt 인증에 graphql middleware를 포함하기 위해서 jwt 인증 설정 다음에 둔다. */
    server.applyMiddleware({
        app
    });
    app.use(graphql_upload_1.graphqlUploadKoa({ maxFileSize: 10000000, maxFiles: 10 }));
    app.use(require('koa-static')(process.cwd()));
    app.use(require('koa-static')(SHELL_MODULE_ROOT_DIR));
    app.use(routes_1.routes.routes());
    app.use(routes_1.routes.allowedMethods());
    app.listen(PORT);
};
bootstrap();
//# sourceMappingURL=server.js.map