@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
102 lines (101 loc) • 3.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../../../models");
function getString(value) {
return typeof value === "string" ? value : null;
}
function getJSON(value) {
if (typeof value === "object" && value !== null) {
return value;
}
if (typeof value === "string") {
try {
return JSON.parse(value);
}
catch {
return undefined;
}
}
return undefined;
}
exports.default = async (req, res) => {
try {
const { foreignId, createIfNotFound } = req.query;
if (!foreignId || typeof foreignId !== "string") {
res.status(400).json({
error: "Missing or invalid foreign user ID.",
code: "user/invalid-identifier",
});
return;
}
const projectId = req.project.id;
const name = getString(req.query.name);
const username = getString(req.query.username);
const avatar = getString(req.query.avatar);
const bio = getString(req.query.bio);
const metadata = getJSON(req.query.metadata);
const secureMetadata = getJSON(req.query.secureMetadata);
let user = await models_1.User.findOne({
where: { foreignId, projectId },
attributes: {
exclude: [
"hash",
"salt",
"email",
"isVerified",
"isActive",
"lastActive",
"secureMetadata",
],
},
});
// Handle case: user not found
if (!user) {
const shouldCreate = createIfNotFound === "true";
const hasPermission = req.isService || req.isMaster;
if (shouldCreate && hasPermission) {
// Create user with provided fields
user = await models_1.User.create({
foreignId,
projectId,
name,
username,
avatar,
bio,
metadata,
secureMetadata,
});
// Fetch again with excluded attributes
const cleanUser = await models_1.User.findByPk(user.id, {
attributes: {
exclude: [
"hash",
"salt",
"email",
"isVerified",
"isActive",
"lastActive",
"secureMetadata",
],
},
});
res.status(201).json(cleanUser?.toJSON());
return;
}
res.status(404).json({
error: "User not found",
code: "user/not-found",
});
return;
}
res.status(200).json(user.toJSON());
}
catch (err) {
console.error("Error fetching or creating user:", err);
res.status(500).json({
error: "Internal server error",
code: "user/server-error",
details: err.message,
});
}
};