@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
96 lines (95 loc) • 3.41 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../../../models");
const sequelize_query_params_1 = require("../../../constants/sequelize-query-params");
const validateEntityUpdated_1 = __importDefault(require("../../../helpers/webhooks/validateEntityUpdated"));
exports.default = async (req, res) => {
const { title, content, attachments, keywords, location, metadata, mentions, } = req.body;
const { entityId } = req.params;
const loggedInUserId = req.userId;
const projectId = req.project.id;
if (!entityId) {
res.status(400).json({
error: "Invalid entity ID.",
code: "entity/invalid-id",
});
return;
}
try {
let entity = (await models_1.Entity.findOne({
where: { projectId, id: entityId },
}));
// If the entity doesn't exist, return a 404 error
if (!entity) {
res.status(404).json({
error: "Entity not found.",
code: "entity/not-found",
});
return;
}
if (entity.userId &&
entity.userId !== loggedInUserId &&
!req.isMaster &&
!req.isService) {
res.status(403).json({
error: "Not authorized to update this entity.",
code: "entity/not-authorized",
});
return;
}
// Call the webhook to validate the entity creation
await (0, validateEntityUpdated_1.default)(req, res, {
projectId,
data: {
foreignId: entity.foreignId,
userId: entity.userId,
title,
content,
attachments,
keywords,
location,
metadata,
mentions,
},
initiatorId: loggedInUserId,
});
// Only update fields that are not undefined
if (title !== undefined)
entity.title = title;
if (content !== undefined)
entity.content = content;
if (attachments !== undefined)
entity.attachments = attachments;
if (keywords !== undefined)
entity.keywords = keywords;
if (metadata !== undefined)
entity.metadata = metadata;
if (mentions !== undefined)
entity.mentions = mentions;
if (location !== undefined)
entity.location = {
type: "Point",
coordinates: [location.longitude, location.latitude],
};
// Save the updated entity
await entity.save();
// Fetch the entity again but populated now
const populatedEntity = (await models_1.Entity.findOne({
where: { id: entity.id },
...sequelize_query_params_1.entityParams,
}));
// Respond with the updated entity
res.status(200).json(populatedEntity.toJSON());
}
catch (err) {
console.error("Failed to update the entity:", err);
res.status(500).json({
error: "Failed to update the entity.",
code: "entity/server-error",
details: err.message,
});
}
};