"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createIndexerManagementServer = void 0;
const stream_1 = require("stream");
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const body_parser_1 = __importDefault(require("body-parser"));
const morgan_1 = __importDefault(require("morgan"));
exports.createIndexerManagementServer = ({ logger, client, port, }) => __awaiter(void 0, void 0, void 0, function* () {
    logger = logger.child({ component: 'IndexerManagementServer' });
    const loggerStream = new stream_1.Stream.Writable();
    loggerStream._write = (chunk, _, next) => {
        logger.debug(chunk.toString().trim());
        next();
    };
    const server = express_1.default();
    // Log requests to the logger stream
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    server.use(morgan_1.default('tiny', { stream: loggerStream }));
    server.use(cors_1.default());
    // Endpoint for health checks
    server.get('/', (_, res) => {
        res.status(200).send('Ready to roll!');
    });
    // GraphQL endpoint
    server.post('/', body_parser_1.default.json(), (req, res) => __awaiter(void 0, void 0, void 0, function* () {
        const { query, variables } = req.body;
        const result = query.startsWith('mutation')
            ? yield client.mutation(query, variables).toPromise()
            : yield client.query(query, variables).toPromise();
        res.status(200).send({
            data: result.data,
            errors: result.error ? result.error.graphQLErrors : null,
            extensions: result.extensions,
        });
    }));
    server.listen(port, () => {
        logger.debug(`Listening on port ${port}`);
    });
    return server;
});
//# sourceMappingURL=server.js.map