@micro.ts/core
Version:
Microservice framework with Typescript
66 lines (65 loc) • 2.76 kB
JavaScript
;
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FastifyBroker = void 0;
const fastify_1 = require("fastify");
const HttpBroker_1 = require("../HttpBroker");
class FastifyBroker extends HttpBroker_1.HttpBroker {
constructor() {
super(...arguments);
this.name = 'FastifyBroker';
this.requestMapper = (r) => __awaiter(this, void 0, void 0, function* () {
const action = {
request: {
headers: r.headers,
body: r.body,
method: r.req.method,
qs: r.query,
params: r.params,
raw: r,
path: r.req.url || '',
},
connection: this.getConnection(),
};
return action;
});
}
paramWrapper(paramName) {
return `:${paramName}`;
}
registerHandler(value, route, method) {
this.server[method](route, (req, res) => __awaiter(this, void 0, void 0, function* () {
const action = yield this.requestMapper(req);
const handler = this.actionToRouteMapper(route, action, value);
const result = yield handler(action);
result.response = result.response || {};
return this.respond(result, res);
}));
}
respond(result, ctx) {
const body = result.response.body || result.response.error;
const headers = result.response.headers || {};
ctx.code(result.response.statusCode || 200);
ctx.headers(headers);
ctx.send(body);
}
start() {
return __awaiter(this, void 0, void 0, function* () {
this.registerRoutes();
yield this.server.listen(Number(this.config.port || 8080), this.config.address);
console.log(`Server listening on address ${this.config.address} and port ${this.config.port}`);
});
}
construct() {
this.server = (0, fastify_1.fastify)();
}
}
exports.FastifyBroker = FastifyBroker;