@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
61 lines (60 loc) • 2.32 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const scoreEntity_1 = __importDefault(require("../../../helpers/scoreEntity"));
const models_1 = require("../../../models");
const sequelize_query_params_1 = require("../../../constants/sequelize-query-params");
exports.default = async (req, res) => {
try {
// Extract entityId from the path.
const { entityId } = req.params;
const projectId = req.project.id;
// Validate the presence of projectId and either foreignId or entityId.
if (entityId && typeof entityId !== "string") {
res.status(400).json({
error: "Missing a valid entityId in request query.",
code: "entity/invalid-resource-id",
});
return;
}
let entity = (await models_1.Entity.findOne({
where: { projectId, id: entityId },
...sequelize_query_params_1.entityParams,
}));
if (!entity) {
res.status(404).json({
error: "Entity not found",
code: "entity/not-found",
});
return;
}
// Convert entity to plain JSON for scoring.
const entityData = entity.toJSON();
// Return the entity with a 200 (OK) status.
res.status(200).json(entityData);
// Schedule the score update asynchronously.
setImmediate(async () => {
try {
const { newScore, newScoreUpdatedAt, updated } = (0, scoreEntity_1.default)(entityData);
if (updated) {
entity.score = newScore;
entity.scoreUpdatedAt = newScoreUpdatedAt;
await entity.save();
}
}
catch (updateErr) {
console.error("Error updating entity score asynchronously: ", updateErr);
}
});
}
catch (err) {
console.error("Error fetching an entity:", err);
res.status(500).json({
error: "Internal server error.",
code: "entity/server-error",
details: err.message,
});
}
};