UNPKG

@replyke/express

Version:

Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.

127 lines (126 loc) 5.51 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const sequelize_1 = require("sequelize"); const models_1 = require("../../../models"); const sequelize_query_params_1 = require("../../../constants/sequelize-query-params"); const createNotification_1 = __importDefault(require("../../../helpers/createNotification")); const models_2 = require("../../../models"); const updateUserReputation_1 = __importDefault(require("../../../helpers/updateUserReputation")); const reputation_scores_1 = __importDefault(require("../../../constants/reputation-scores")); const validateEntityCreated_1 = __importDefault(require("../../../helpers/webhooks/validateEntityCreated")); const config_1 = require("../../../config"); exports.default = async (req, res) => { const { sequelize, handlers } = (0, config_1.getCoreConfig)(); try { const { userId: userIdProp, // Not passed from React libraries hook, but could be passed from server using the js sdk foreignId, sourceId, title, content, attachments, keywords, mentions, location, metadata, excludeUserId, } = req.body; const loggedInUserId = req.userId; const projectId = req.project.id; // UserId doesn't have to be provided, as some entities can just be automatically created when a user visits. But if a userId is provided as the user that created the entity, then it must match the logged in user ID. if (userIdProp !== undefined && userIdProp !== loggedInUserId && !req.isMaster && !req.isService) { res.status(403).json({ error: "User is not authorized to create this entity.", code: "entity/unauthorized", }); return; } const userId = excludeUserId ? undefined : userIdProp ?? loggedInUserId; console.log({ userId }); const newEntityData = { projectId, referenceId: foreignId, foreignId: foreignId, sourceId, userId, title, content, attachments, keywords, mentions, location: location ? { type: "Point", coordinates: [location.longitude, location.latitude], } : undefined, metadata, }; const { projectId: _, ...restOfEntityData } = newEntityData; // Call the webhook to validate the entity creation await (0, validateEntityCreated_1.default)(req, res, { projectId, data: restOfEntityData, initiatorId: loggedInUserId, }); const { entity } = await sequelize.transaction(async (transaction) => { // Create a new entity using Sequelize's create method const entity = (await models_1.Entity.create({ ...newEntityData, mentions, }, { transaction })); await entity.save({ transaction }); if (userId) { await (0, updateUserReputation_1.default)(userId, reputation_scores_1.default.createEntity, transaction); } return { entity }; }); await handlers.createEntity({ projectId }); // Fetch the entity again but populated now const populatedEntity = (await models_1.Entity.findOne({ where: { id: entity.id }, ...sequelize_query_params_1.entityParams, })); // Return the newly created entity with a 200 (OK) status res.status(200).json(populatedEntity.toJSON()); // Trigger the notification in the background if (!entity.mentions) return; // Fetch the project to ensure it exists (optional but recommended) const user = (await models_2.User.findByPk(loggedInUserId)); if (!user) return; entity.mentions.forEach((mention) => { if (mention.id !== entity.userId) { (0, createNotification_1.default)(req, res, { userId: entity.userId, projectId, type: "entity-mention", action: "open-entity", metadata: { entityId: entity.id, entityShortId: entity.shortId, entityTitle: entity.title, entityContent: (entity.content || "").slice(0, 200), initiatorId: loggedInUserId, initiatorName: user.name, initiatorUsername: user.username, initiatorAvatar: user.avatar, }, }); } }); } catch (err) { if (err instanceof sequelize_1.ForeignKeyConstraintError) { res.status(400).json({ error: "Invalid projectId, project does not exist.", code: "report/invalid-foreign-key", details: err.message, }); return; } console.error("Error creating an entity:", err); res.status(500).json({ error: "Internal server error.", code: "entity/server-error", details: err.message, }); return; } };