This commit is contained in:
Alex Holliday committed 2025-07-21 10:34:16 -07:00
1 parent 846564a17e
commit bfa6832beb
83 files changed
+338 -1249

No files matched your search

+1 -4
View File
@@ -156,10 +156,7 @@ MonitorSchema.pre("deleteMany", async function (next) {
} else {
await Check.deleteMany({ monitorId: monitor._id });
}
await StatusPage.updateMany(
{ monitors: monitor._id },
{ $pull: { monitors: monitor._id } }
);
await StatusPage.updateMany({ monitors: monitor._id }, { $pull: { monitors: monitor._id } });
await MonitorStats.deleteMany({ monitorId: monitor._id.toString() });
}
next();
+1 -2
View File
@@ -89,8 +89,7 @@ class MongoDB {
connect = async () => {
try {
const connectionString =
this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
const connectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString);
// If there are no AppSettings, create one
await AppSettings.findOneAndUpdate(
+7 -40
View File
@@ -58,26 +58,13 @@ const createChecks = async (checks) => {
* @returns {Promise<Array<Check>>}
* @throws {Error}
*/
const getChecksByMonitor = async ({
monitorId,
type,
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
status,
}) => {
const getChecksByMonitor = async ({ monitorId, type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status }) => {
try {
status = status === "true" ? true : status === "false" ? false : undefined;
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
const ackStage =
ack === "true"
? { ack: true }
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
// Match
const matchStage = {
@@ -158,23 +145,12 @@ const getChecksByMonitor = async ({
}
};
const getChecksByTeam = async ({
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
teamId,
}) => {
const getChecksByTeam = async ({ sortOrder, dateRange, filter, ack, page, rowsPerPage, teamId }) => {
try {
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
const ackStage =
ack === "true"
? { ack: true }
: { $or: [{ ack: false }, { ack: { $exists: false } }] };
const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] };
const matchStage = {
teamId: new ObjectId(teamId),
@@ -264,11 +240,7 @@ const getChecksByTeam = async ({
*/
const ackCheck = async (checkId, teamId, ack) => {
try {
const updatedCheck = await Check.findOneAndUpdate(
{ _id: checkId, teamId: teamId },
{ $set: { ack, ackAt: new Date() } },
{ new: true }
);
const updatedCheck = await Check.findOneAndUpdate({ _id: checkId, teamId: teamId }, { $set: { ack, ackAt: new Date() } }, { new: true });
if (!updatedCheck) {
throw new Error("Check not found");
@@ -293,10 +265,7 @@ const ackCheck = async (checkId, teamId, ack) => {
*/
const ackAllChecks = async (monitorId, teamId, ack, path) => {
try {
const updatedChecks = await Check.updateMany(
path === "monitor" ? { monitorId } : { teamId },
{ $set: { ack, ackAt: new Date() } }
);
const updatedChecks = await Check.updateMany(path === "monitor" ? { monitorId } : { teamId }, { $set: { ack, ackAt: new Date() } });
return updatedChecks.modifiedCount;
} catch (error) {
error.service = SERVICE_NAME;
@@ -317,9 +286,7 @@ const getChecksSummaryByTeamId = async ({ teamId }) => {
const matchStage = {
teamId: new ObjectId(teamId),
};
const checks = await Check.aggregate(
buildChecksSummaryByTeamIdPipeline({ matchStage })
);
const checks = await Check.aggregate(buildChecksSummaryByTeamIdPipeline({ matchStage }));
return checks[0].summary;
} catch (error) {
error.service = SERVICE_NAME;
+2 -10
View File
@@ -10,20 +10,12 @@ const buildChecksSummaryByTeamIdPipeline = ({ matchStage }) => {
totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } },
resolvedChecks: {
$sum: {
$cond: [
{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] },
1,
0,
],
$cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0],
},
},
downChecks: {
$sum: {
$cond: [
{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] },
1,
0,
],
$cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0],
},
},
cannotResolveChecks: {
+3 -11
View File
@@ -2,11 +2,7 @@ import Monitor from "../../models/Monitor.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "diagnosticModule";
import {
buildMonitorSummaryByTeamIdPipeline,
buildMonitorsByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline,
} from "./monitorModuleQueries.js";
import { buildMonitorSummaryByTeamIdPipeline, buildMonitorsByTeamIdPipeline, buildFilteredMonitorsByTeamIdPipeline } from "./monitorModuleQueries.js";
const getMonitorsByTeamIdExecutionStats = async (req) => {
try {
@@ -24,13 +20,9 @@ const getMonitorsByTeamIdExecutionStats = async (req) => {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summary = await Monitor.aggregate(
buildMonitorSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
const summary = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
const monitors = await Monitor.aggregate(
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
).explain("executionStats");
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order })).explain("executionStats");
const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
@@ -23,14 +23,10 @@ const createHardwareCheck = async (hardwareCheckData) => {
if (monitor.uptimePercentage === undefined) {
newUptimePercentage = status === true ? 1 : 0;
} else {
newUptimePercentage =
(monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
newUptimePercentage = (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
}
await Monitor.findOneAndUpdate(
{ _id: monitorId },
{ uptimePercentage: newUptimePercentage }
);
await Monitor.findOneAndUpdate({ _id: monitorId }, { uptimePercentage: newUptimePercentage });
const hardwareCheck = await new HardwareCheck({
...hardwareCheckData,
@@ -63,8 +63,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount =
await MaintenanceWindow.countDocuments(maintenanceQuery);
const maintenanceWindowCount = await MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination
let skip = 0;
@@ -78,10 +77,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
sort[field] = order === "asc" ? 1 : -1;
}
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery)
.skip(skip)
.limit(rowsPerPage)
.sort(sort);
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
return { maintenanceWindows, maintenanceWindowCount };
} catch (error) {
@@ -122,8 +118,7 @@ const getMaintenanceWindowsByMonitorId = async (monitorId) => {
*/
const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
try {
const maintenanceWindow =
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
const maintenanceWindow = await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
@@ -174,11 +169,7 @@ const deleteMaintenanceWindowByUserId = async (userId) => {
const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => {
try {
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(
maintenanceWindowId,
maintenanceWindowData,
{ new: true }
);
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(maintenanceWindowId, maintenanceWindowData, { new: true });
return editedMaintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
+19 -92
View File
@@ -285,10 +285,7 @@ const groupChecksByTime = (checks, dateRange) => {
return acc;
}
const time =
dateRange === "day"
? checkDate.setMinutes(0, 0, 0)
: checkDate.toISOString().split("T")[0];
const time = dateRange === "day" ? checkDate.setMinutes(0, 0, 0) : checkDate.toISOString().split("T")[0];
if (!acc[time]) {
acc[time] = { time, checks: [] };
@@ -306,9 +303,7 @@ const groupChecksByTime = (checks, dateRange) => {
const calculateGroupStats = (group) => {
const totalChecks = group.checks.length;
const checksWithResponseTime = group.checks.filter(
(check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)
);
const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime));
return {
time: group.time,
@@ -317,8 +312,7 @@ const calculateGroupStats = (group) => {
totalIncidents: group.checks.filter((check) => !check.status).length,
avgResponseTime:
checksWithResponseTime.length > 0
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) /
checksWithResponseTime.length
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / checksWithResponseTime.length
: 0,
};
};
@@ -344,29 +338,15 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
const dateString = formatLookup[dateRange];
const results = await Check.aggregate(
buildUptimeDetailsPipeline(monitorId, dates, dateString)
);
const results = await Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString));
const monitorData = results[0];
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(
monitorData.groupedUpChecks,
10,
100
);
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100);
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(
monitorData.groupedDownChecks,
10,
100
);
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100);
const normalizedGroupChecks = NormalizeDataUptimeDetails(
monitorData.groupedChecks,
10,
100
);
const normalizedGroupChecks = NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100);
monitorData.groupedChecks = normalizedGroupChecks;
const monitorStats = await MonitorStats.findOne({ monitorId });
@@ -386,14 +366,7 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorStatsById = async ({
monitorId,
limit,
sortOrder,
dateRange,
numToDisplay,
normalize,
}) => {
const getMonitorStatsById = async ({ monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
// Get monitor, if we can't find it, abort with error
@@ -408,12 +381,7 @@ const getMonitorStatsById = async ({
// Get Checks for monitor in date range requested
const model = CHECK_MODEL_LOOKUP[monitor.type];
const dates = getDateRange(dateRange);
const { checksAll, checksForDateRange } = await getMonitorChecks(
monitorId,
model,
dates,
sort
);
const { checksAll, checksForDateRange } = await getMonitorChecks(monitorId, model, dates, sort);
// Build monitor stats
const monitorStats = {
@@ -423,20 +391,10 @@ const getMonitorStatsById = async ({
latestResponseTime: getLatestResponseTime(checksAll),
periodIncidents: getIncidents(checksForDateRange),
periodTotalChecks: checksForDateRange.length,
checks: processChecksForDisplay(
NormalizeData,
checksForDateRange,
numToDisplay,
normalize
),
checks: processChecksForDisplay(NormalizeData, checksForDateRange, numToDisplay, normalize),
};
if (
monitor.type === "http" ||
monitor.type === "ping" ||
monitor.type === "docker" ||
monitor.type === "port"
) {
if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port") {
// HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange);
monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
@@ -463,9 +421,7 @@ const getHardwareDetailsById = async ({ monitorId, dateRange }) => {
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const hardwareStats = await HardwareCheck.aggregate(
buildHardwareDetailsPipeline(monitor, dates, dateString)
);
const hardwareStats = await HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString));
const monitorStats = {
...monitor.toObject(),
@@ -505,16 +461,7 @@ const getMonitorById = async (monitorId) => {
}
};
const getMonitorsByTeamId = async ({
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
teamId,
}) => {
const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
@@ -528,14 +475,10 @@ const getMonitorsByTeamId = async ({
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summaryResult = await Monitor.aggregate(
buildMonitorSummaryByTeamIdPipeline({ matchStage })
);
const summaryResult = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage }));
const summary = summaryResult[0];
const monitors = await Monitor.aggregate(
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
);
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order }));
const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
@@ -569,14 +512,10 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
}
if (explain === true) {
return Monitor.aggregate(
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
return Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
}
const queryResult = await Monitor.aggregate(
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
);
const queryResult = await Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage }));
const { monitors, summary } = queryResult?.[0] ?? {};
return { monitors, summary };
} catch (error) {
@@ -586,17 +525,7 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
}
};
const getMonitorsWithChecksByTeamId = async ({
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
teamId,
explain,
}) => {
const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => {
try {
limit = parseInt(limit);
page = parseInt(page);
@@ -684,9 +613,7 @@ const createMonitor = async ({ body, teamId, userId }) => {
*/
const createBulkMonitors = async (req) => {
try {
const monitors = req.map(
(item) => new Monitor({ ...item, notifications: undefined })
);
const monitors = req.map((item) => new Monitor({ ...item, notifications: undefined }));
await Monitor.bulkSave(monitors);
return monitors;
} catch (error) {
+12 -64
View File
@@ -31,11 +31,7 @@ const buildUptimeDetailsPipeline = (monitorId, dates, dateString) => {
$project: {
_id: 0,
percentage: {
$cond: [
{ $eq: ["$totalChecks", 0] },
0,
{ $divide: ["$upChecks", "$totalChecks"] },
],
$cond: [{ $eq: ["$totalChecks", 0] }, 0, { $divide: ["$upChecks", "$totalChecks"] }],
},
},
},
@@ -235,11 +231,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
{
$match: {
$expr: {
$and: [
{ $eq: ["$monitorId", monitor._id] },
{ $gte: ["$createdAt", dates.start] },
{ $lte: ["$createdAt", dates.end] },
],
$and: [{ $eq: ["$monitorId", monitor._id] }, { $gte: ["$createdAt", dates.start] }, { $lte: ["$createdAt", dates.end] }],
},
},
},
@@ -326,10 +318,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks",
as: "diskArray",
in: {
$arrayElemAt: [
"$$diskArray.read_speed_bytes",
"$$diskIndex",
],
$arrayElemAt: ["$$diskArray.read_speed_bytes", "$$diskIndex"],
},
},
},
@@ -340,10 +329,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks",
as: "diskArray",
in: {
$arrayElemAt: [
"$$diskArray.write_speed_bytes",
"$$diskIndex",
],
$arrayElemAt: ["$$diskArray.write_speed_bytes", "$$diskIndex"],
},
},
},
@@ -354,10 +340,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks",
as: "diskArray",
in: {
$arrayElemAt: [
"$$diskArray.total_bytes",
"$$diskIndex",
],
$arrayElemAt: ["$$diskArray.total_bytes", "$$diskIndex"],
},
},
},
@@ -379,10 +362,7 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => {
input: "$disks",
as: "diskArray",
in: {
$arrayElemAt: [
"$$diskArray.usage_percent",
"$$diskIndex",
],
$arrayElemAt: ["$$diskArray.usage_percent", "$$diskIndex"],
},
},
},
@@ -556,26 +536,14 @@ const buildMonitorsAndSummaryByTeamIdPipeline = ({ matchStage }) => {
];
};
const buildMonitorsWithChecksByTeamIdPipeline = ({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
}) => {
const buildMonitorsWithChecksByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
const skip = page && rowsPerPage ? page * rowsPerPage : 0;
const sort = { [field]: order === "asc" ? 1 : -1 };
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
// Match name
if (typeof filter !== "undefined" && field === "name") {
matchStage.$or = [
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
];
matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
}
// Match isActive
@@ -667,37 +635,20 @@ const buildMonitorsWithChecksByTeamIdPipeline = ({
return pipeline;
};
const buildFilteredMonitorsByTeamIdPipeline = ({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
}) => {
const buildFilteredMonitorsByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => {
const skip = page && rowsPerPage ? page * rowsPerPage : 0;
const sort = { [field]: order === "asc" ? 1 : -1 };
const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : [];
if (typeof filter !== "undefined" && field === "name") {
matchStage.$or = [
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
];
matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
}
if (typeof filter !== "undefined" && field === "status") {
matchStage.status = filter === "true";
}
const pipeline = [
{ $match: matchStage },
{ $sort: sort },
{ $skip: skip },
...limitStage,
];
const pipeline = [{ $match: matchStage }, { $sort: sort }, { $skip: skip }, ...limitStage];
// Add checks
if (limit) {
@@ -792,10 +743,7 @@ const buildGetMonitorsByTeamIdPipeline = (req) => {
? [
{
$match: {
$or: [
{ name: { $regex: filter, $options: "i" } },
{ url: { $regex: filter, $options: "i" } },
],
$or: [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }],
},
},
]
@@ -32,9 +32,7 @@ const createNetworkCheck = async (networkCheckData) => {
*/
const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
try {
const networkChecks = await NetworkCheck.find({ monitorId })
.sort({ createdAt: -1 })
.limit(limit);
const networkChecks = await NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
return networkChecks;
} catch (error) {
error.service = SERVICE_NAME;
+1 -3
View File
@@ -29,9 +29,7 @@ const updateAppSettings = async (newSettings) => {
await AppSettings.findOneAndUpdate({}, update, {
upsert: true,
});
const settings = await AppSettings.findOne()
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
const settings = await AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
return settings;
} catch (error) {
error.service = SERVICE_NAME;
+5 -20
View File
@@ -48,13 +48,9 @@ const updateStatusPage = async (statusPageData, image) => {
if (statusPageData.deleteSubmonitors === "true") {
statusPageData.subMonitors = [];
}
const statusPage = await StatusPage.findOneAndUpdate(
{ url: statusPageData.url },
statusPageData,
{
new: true,
}
);
const statusPage = await StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
new: true,
});
return statusPage;
} catch (error) {
@@ -98,19 +94,8 @@ const getStatusPage = async (url) => {
}
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) {
const {
_id,
color,
companyName,
isPublished,
logo,
originalMonitors,
showCharts,
showUptimePercentage,
timezone,
showAdminLoginLink,
url,
} = preliminaryStatusPage;
const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } =
preliminaryStatusPage;
return {
statusPage: {
_id,
+4 -24
View File
@@ -16,11 +16,7 @@ const SERVICE_NAME = "userModule";
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const insertUser = async (
userData,
imageFile,
generateAvatarImage = GenerateAvatarImage
) => {
const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAvatarImage) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
if (imageFile) {
@@ -47,9 +43,7 @@ const insertUser = async (
const newUser = new UserModel(userData);
await newUser.save();
return await UserModel.findOne({ _id: newUser._id })
.select("-password")
.select("-profileImage"); // .select() doesn't work with create, need to save then find
return await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) {
if (error.code === DUPLICATE_KEY_CODE) {
error.message = stringService.dbUserExists;
@@ -98,12 +92,7 @@ const getUserByEmail = async (email) => {
* @throws {Error}
*/
const updateUser = async (
req,
res,
parseBoolean = ParseBoolean,
generateAvatarImage = GenerateAvatarImage
) => {
const updateUser = async (req, res, parseBoolean = ParseBoolean, generateAvatarImage = GenerateAvatarImage) => {
const candidateUserId = req.params.userId;
try {
const candidateUser = { ...req.body };
@@ -220,13 +209,4 @@ const logoutUser = async (userId) => {
}
};
export {
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
};
export { insertUser, getUserByEmail, updateUser, deleteUser, deleteTeam, deleteAllOtherUsers, getAllUsers, logoutUser };