@mediarithmics/plugins-nodejs-sdk
Version:
This is the mediarithmics nodejs to help plugin developers bootstrapping their plugin without having to deal with most of the plugin boilerplate
177 lines (176 loc) • 8.86 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const index_1 = require("../../../index");
class AudienceFeedConnectorBasePlugin extends index_1.BasePlugin {
fetchAudienceSegment(feedId) {
const _super = name => super[name];
return __awaiter(this, void 0, void 0, function* () {
const response = yield _super("requestGatewayHelper").call(this, "GET", `${this.outboundPlatformUrl}/v1/audience_segment_external_feeds/${feedId}/audience_segment`);
this.logger.debug(`Fetched External Segment: FeedId: ${feedId} - ${JSON.stringify(response.data)}`);
return response.data;
});
}
fetchAudienceFeed(feedId) {
const _super = name => super[name];
return __awaiter(this, void 0, void 0, function* () {
const response = yield _super("requestGatewayHelper").call(this, "GET", `${this.outboundPlatformUrl}/v1/audience_segment_external_feeds/${feedId}`);
this.logger.debug(`Fetched External Feed: ${feedId} - ${JSON.stringify(response.data)}`);
return response.data;
});
}
fetchAudienceFeedProperties(feedId) {
const _super = name => super[name];
return __awaiter(this, void 0, void 0, function* () {
const response = yield _super("requestGatewayHelper").call(this, "GET", `${this.outboundPlatformUrl}/v1/audience_segment_external_feeds/${feedId}/properties`);
this.logger.debug(`Fetched External Feed Properties: ${feedId} - ${JSON.stringify(response.data)}`);
return response.data;
});
}
// Method to build an instance context
// To be overriden to get a cutom behavior
// This is a default provided implementation
instanceContextBuilder(feedId) {
return __awaiter(this, void 0, void 0, function* () {
const audienceFeedP = this.fetchAudienceFeed(feedId);
const audienceFeedPropsP = this.fetchAudienceFeedProperties(feedId);
const results = yield Promise.all([audienceFeedP, audienceFeedPropsP]);
const audienceFeed = results[0];
const audienceFeedProps = results[1];
const context = {
feed: audienceFeed,
feedProperties: audienceFeedProps
};
return context;
});
}
emptyBodyFilter(req, res, next) {
if (!req.body || _.isEmpty(req.body)) {
const msg = {
error: "Missing request body"
};
this.logger.error(`POST /v1/${req.url} : %s`, JSON.stringify(msg));
res.status(500).json(msg);
}
else {
next();
}
}
getInstanceContext(feedId) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.pluginCache.get(feedId)) {
this.pluginCache.put(feedId, this.instanceContextBuilder(feedId), this.INSTANCE_CONTEXT_CACHE_EXPIRATION);
}
return this.pluginCache.get(feedId);
});
}
initExternalSegmentCreation() {
this.app.post("/v1/external_segment_creation", this.emptyBodyFilter, (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
this.logger.debug(`POST /v1/external_segment_creation ${JSON.stringify(req.body)}`);
const request = req.body;
if (!this.onExternalSegmentCreation) {
throw new Error("No External Segment Creation listener registered!");
}
const instanceContext = yield this.getInstanceContext(request.feed_id);
const response = yield this.onExternalSegmentCreation(request, instanceContext);
this.logger.debug(`Returning: ${JSON.stringify(response)}`);
const pluginResponse = {
status: response.status
};
if (response.message) {
pluginResponse.message = response.message;
}
const statusCode = (response.status === 'ok') ? 200 : 500;
return res.status(statusCode).send(JSON.stringify(pluginResponse));
}
catch (error) {
this.logger.error(`Something bad happened : ${error.message} - ${error.stack}`);
return res.status(500).send({ status: 'error', message: `${error.message}\n ${error.stack}` });
}
}));
}
initExternalSegmentConnection() {
this.app.post("/v1/external_segment_connection", this.emptyBodyFilter, (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
this.logger.debug(`POST /v1/external_segment_connection ${JSON.stringify(req.body)}`);
const request = req.body;
if (!this.onExternalSegmentConnection) {
throw new Error("No External Segment Connection listener registered!");
}
const instanceContext = yield this.getInstanceContext(request.feed_id);
const response = yield this.onExternalSegmentConnection(request, instanceContext);
this.logger.debug(`FeedId: ${request.feed_id} - Plugin impl returned: ${JSON.stringify(response)}`);
const pluginResponse = {
status: response.status
};
if (response.message) {
pluginResponse.message = response.message;
}
let statusCode;
switch (response.status) {
case 'external_segment_not_ready_yet':
statusCode = 502;
break;
case 'ok':
statusCode = 200;
break;
case 'error':
statusCode = 500;
break;
default:
statusCode = 500;
}
this.logger.debug(`FeedId: ${request.feed_id} - Returning: ${statusCode} - ${JSON.stringify(response)}`);
return res.status(statusCode).send(JSON.stringify(pluginResponse));
}
catch (error) {
this.logger.error(`Something bad happened : ${error.message} - ${error.stack}`);
return res.status(500).send({ status: 'error', message: `${error.message}\n ${error.stack}` });
}
}));
}
initUserSegmentUpdate() {
this.app.post("/v1/user_segment_update", this.emptyBodyFilter, (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
this.logger.debug(`POST /v1/user_segment_update ${JSON.stringify(req.body)}`);
const request = req.body;
if (!this.onUserSegmentUpdate) {
throw new Error("No User Segment Update listener registered!");
}
const instanceContext = yield this.getInstanceContext(request.feed_id);
const response = yield this.onUserSegmentUpdate(request, instanceContext);
this.logger.debug(`Returning: ${JSON.stringify(response)}`);
const pluginResponse = {
status: response.status
};
if (response.nextMsgDelayInMs) {
res.set("x-mics-next-msg-delay", response.nextMsgDelayInMs.toString());
}
if (response.message) {
pluginResponse.message = response.message;
}
return res.status(200).send(JSON.stringify(pluginResponse));
}
catch (error) {
this.logger.error(`Something bad happened : ${error.message} - ${error.stack}`);
return res.status(500).send({ status: 'error', message: `${error.message}\n ${error.stack}` });
}
}));
}
constructor() {
super();
this.initExternalSegmentCreation();
this.initExternalSegmentConnection();
this.initUserSegmentUpdate();
}
}
exports.AudienceFeedConnectorBasePlugin = AudienceFeedConnectorBasePlugin;