import { Const } from '@basemaps/shared';
import { HttpHeader, LambdaHttpResponse } from '@linzjs/lambda';
export class Router {
    constructor() {
        this.handlers = {};
    }
    static action(req) {
        const path = req.path;
        const [version, name, ...rest] = (path[0] === '/' ? path.slice(1) : path)
            .split('/')
            .map((c) => decodeURIComponent(c));
        if (name == null)
            return { version: 'v1', name: version, rest: [] };
        return { version, name: name, rest };
    }
    static apiKey(req) {
        var _a;
        const apiKey = (_a = req.query.get(Const.ApiKey.QueryString)) !== null && _a !== void 0 ? _a : req.header('X-LINZ-Api-Key');
        if (apiKey != null && !Array.isArray(apiKey)) {
            req.set(Const.ApiKey.QueryString, this.apiKey);
            return apiKey;
        }
        return;
    }
    async handle(req) {
        // Allow cross origin requests
        if (req.method === 'options') {
            return new LambdaHttpResponse(200, 'Options', {
                [HttpHeader.Cors]: '*',
                'Access-Control-Allow-Credentials': 'false',
                'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE',
            });
        }
        if (req.method !== 'GET')
            return new LambdaHttpResponse(405, 'Method not allowed');
        const action = Router.action(req);
        const handler = action.version === 'v1' ? this.handlers[action.name] : null;
        if (handler == null)
            return new LambdaHttpResponse(404, 'Not Found');
        const response = await handler(req);
        response.header(HttpHeader.Cors, '*');
        return response;
    }
    get(path, handler) {
        if (this.handlers[path] != null)
            throw new Error(path + ' already registered');
        this.handlers[path] = handler;
    }
}
//# sourceMappingURL=router.js.map