@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
92 lines (91 loc) • 3.35 kB
JavaScript
"use strict";
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 sanitizeUsername_1 = __importDefault(require("../../../helpers/sanitizeUsername"));
const validateUserUpdated_1 = __importDefault(require("../../../helpers/webhooks/validateUserUpdated"));
const reduceAuthenticatedUserDetails_1 = __importDefault(require("../../../helpers/reduceAuthenticatedUserDetails"));
exports.default = async (req, res) => {
try {
const { update } = req.body;
const { userId } = req.params;
const projectId = req.project.id;
// Validate the presence of required data.
if (!userId || !update || Object.keys(update).length === 0) {
res.status(400).json({
error: "Missing required data",
code: "user/missing-data",
});
return;
}
// Find the comment by projectId and commentId
const user = await models_1.User.findOne({
where: {
id: userId,
projectId,
},
});
// If no user is found, return a 404 (Not Found) status.
if (!user) {
res.status(404).json({
error: "User not found",
code: "user/not-found",
});
return;
}
const { name, username, avatar, bio, birthdate, location, metadata, secureMetadata, } = update;
const sanitizedUpdate = {
name,
username,
avatar,
bio,
birthdate,
location,
metadata,
secureMetadata,
};
if (sanitizedUpdate.username) {
sanitizedUpdate.username = (0, sanitizeUsername_1.default)(update.username);
}
if (sanitizedUpdate.location) {
sanitizedUpdate.location = {
type: "Point",
coordinates: [update.location.longitude, update.location.latitude],
};
}
// Call the webhook to validate the user creation
await (0, validateUserUpdated_1.default)(req, res, update);
// Update the user with the provided update content.
await user.update(update);
// get the target model for that alias:
const SuspensionModel = models_1.User.associations.suspensions
.target;
const ActiveSuspensionModel = SuspensionModel.scope({
method: ["active", new Date()],
});
// Reload the user to ensure the latest data is fetched.
await user.reload({
include: [
{
model: ActiveSuspensionModel,
as: "suspensions",
required: false,
},
],
});
// Return the updated user.
res
.status(200)
.json((0, reduceAuthenticatedUserDetails_1.default)(user));
}
catch (err) {
console.error("Error updating a user: ", err);
res.status(500).json({
error: "Internal server error",
code: "user/server-error",
details: err.message,
});
}
};