🐛 fix findOneAndUpdate

This commit is contained in:
Flam3rboy 2021-08-18 11:47:28 +02:00
parent bf8718489e
commit 9ab8fc8e6e
17 changed files with 43 additions and 40 deletions

View File

@ -12,9 +12,6 @@ import { initRateLimits } from "./middlewares/RateLimit";
import TestClient from "./middlewares/TestClient"; import TestClient from "./middlewares/TestClient";
import { initTranslation } from "./middlewares/Translation"; import { initTranslation } from "./middlewares/Translation";
// this will return the new updated document for findOneAndUpdate
mongoose.set("returnOriginal", false); // https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndUpdate
export interface FosscordServerOptions extends ServerOptions {} export interface FosscordServerOptions extends ServerOptions {}
declare global { declare global {

View File

@ -43,7 +43,7 @@ router.patch("/", check(ChannelModifySchema), async (req: Request, res: Response
const permission = await getPermission(req.user_id, undefined, channel_id); const permission = await getPermission(req.user_id, undefined, channel_id);
permission.hasThrow("MANAGE_CHANNELS"); permission.hasThrow("MANAGE_CHANNELS");
const channel = await ChannelModel.findOneAndUpdate({ id: channel_id }, payload).exec(); const channel = await ChannelModel.findOneAndUpdate({ id: channel_id }, payload, { new: true }).exec();
const data = toObject(channel); const data = toObject(channel);

View File

@ -43,7 +43,7 @@ router.delete("/", async (req: Request, res: Response) => {
const permissions = await getPermission(req.user_id, undefined, channel_id); const permissions = await getPermission(req.user_id, undefined, channel_id);
permissions.hasThrow("MANAGE_MESSAGES"); permissions.hasThrow("MANAGE_MESSAGES");
await MessageModel.findOneAndUpdate({ id: message_id, channel_id }, { reactions: [] }).exec(); await MessageModel.findOneAndUpdate({ id: message_id, channel_id }, { reactions: [] }, { new: true }).exec();
await emitEvent({ await emitEvent({
event: "MESSAGE_REACTION_REMOVE_ALL", event: "MESSAGE_REACTION_REMOVE_ALL",

View File

@ -5,7 +5,8 @@ import {
emitEvent, emitEvent,
getPermission, getPermission,
MemberModel, MemberModel,
RoleModel RoleModel,
toObject
} from "@fosscord/util"; } from "@fosscord/util";
import { Router, Response, Request } from "express"; import { Router, Response, Request } from "express";
import { HTTPError } from "lambert-server"; import { HTTPError } from "lambert-server";
@ -47,12 +48,12 @@ router.put("/:overwrite_id", check({ allow: String, deny: String, type: Number,
overwrite.deny = body.deny; overwrite.deny = body.deny;
// @ts-ignore // @ts-ignore
channel = await ChannelModel.findOneAndUpdate({ id: channel_id }, channel).exec(); channel = await ChannelModel.findOneAndUpdate({ id: channel_id }, channel, { new: true }).exec();
await emitEvent({ await emitEvent({
event: "CHANNEL_UPDATE", event: "CHANNEL_UPDATE",
channel_id, channel_id,
data: channel data: toObject(channel)
} as ChannelUpdateEvent); } as ChannelUpdateEvent);
return res.sendStatus(204); return res.sendStatus(204);
@ -65,13 +66,17 @@ router.delete("/:overwrite_id", async (req: Request, res: Response) => {
const permissions = await getPermission(req.user_id, undefined, channel_id); const permissions = await getPermission(req.user_id, undefined, channel_id);
permissions.hasThrow("MANAGE_ROLES"); permissions.hasThrow("MANAGE_ROLES");
const channel = await ChannelModel.findOneAndUpdate({ id: channel_id }, { $pull: { permission_overwrites: { id: overwrite_id } } }); const channel = await ChannelModel.findOneAndUpdate(
{ id: channel_id },
{ $pull: { permission_overwrites: { id: overwrite_id } } },
{ new: true }
);
if (!channel.guild_id) throw new HTTPError("Channel not found", 404); if (!channel.guild_id) throw new HTTPError("Channel not found", 404);
await emitEvent({ await emitEvent({
event: "CHANNEL_UPDATE", event: "CHANNEL_UPDATE",
channel_id, channel_id,
data: channel data: toObject(channel)
} as ChannelUpdateEvent); } as ChannelUpdateEvent);
return res.sendStatus(204); return res.sendStatus(204);

View File

@ -57,7 +57,7 @@ router.delete("/:message_id", async (req: Request, res: Response) => {
permission.hasThrow("VIEW_CHANNEL"); permission.hasThrow("VIEW_CHANNEL");
if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES"); if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES");
const message = toObject(await MessageModel.findOneAndUpdate({ id: message_id }, { pinned: false }).exec()); const message = toObject(await MessageModel.findOneAndUpdate({ id: message_id }, { pinned: false }, { new: true }).exec());
await emitEvent({ await emitEvent({
event: "MESSAGE_UPDATE", event: "MESSAGE_UPDATE",

View File

@ -1,16 +1,5 @@
import { Router, Response, Request } from "express"; import { Router, Response, Request } from "express";
import { import { ChannelModel, toObject, ChannelUpdateEvent, getPermission, emitEvent } from "@fosscord/util";
ChannelCreateEvent,
ChannelModel,
ChannelType,
GuildModel,
Snowflake,
toObject,
ChannelUpdateEvent,
AnyChannel,
getPermission,
emitEvent
} from "@fosscord/util";
import { HTTPError } from "lambert-server"; import { HTTPError } from "lambert-server";
import { ChannelModifySchema } from "../../../schema/Channel"; import { ChannelModifySchema } from "../../../schema/Channel";
@ -63,7 +52,7 @@ router.patch(
} }
} }
const channel = await ChannelModel.findOneAndUpdate({ id: req.body, guild_id }, opts).exec(); const channel = await ChannelModel.findOneAndUpdate({ id: req.body, guild_id }, opts, { new: true }).exec();
await emitEvent({ event: "CHANNEL_UPDATE", data: toObject(channel), channel_id: body.id, guild_id } as ChannelUpdateEvent); await emitEvent({ event: "CHANNEL_UPDATE", data: toObject(channel), channel_id: body.id, guild_id } as ChannelUpdateEvent);

View File

@ -48,7 +48,7 @@ router.patch("/", check(GuildUpdateSchema), async (req: Request, res: Response)
if (body.banner) body.banner = await handleFile(`/banners/${guild_id}`, body.banner); if (body.banner) body.banner = await handleFile(`/banners/${guild_id}`, body.banner);
if (body.splash) body.splash = await handleFile(`/splashes/${guild_id}`, body.splash); if (body.splash) body.splash = await handleFile(`/splashes/${guild_id}`, body.splash);
const guild = await GuildModel.findOneAndUpdate({ id: guild_id }, body) const guild = await GuildModel.findOneAndUpdate({ id: guild_id }, body, { new: true })
.populate({ path: "joined_at", match: { id: req.user_id } }) .populate({ path: "joined_at", match: { id: req.user_id } })
.exec(); .exec();

View File

@ -36,7 +36,7 @@ router.patch("/", check(MemberChangeSchema), async (req: Request, res: Response)
// TODO: check if user has permission to add role // TODO: check if user has permission to add role
} }
const member = await MemberModel.findOneAndUpdate({ id: member_id, guild_id }, body).exec(); const member = await MemberModel.findOneAndUpdate({ id: member_id, guild_id }, body, { new: true }).exec();
await emitEvent({ await emitEvent({
event: "GUILD_MEMBER_UPDATE", event: "GUILD_MEMBER_UPDATE",

View File

@ -108,7 +108,8 @@ router.patch("/:role_id", check(RoleModifySchema), async (req: Request, res: Res
guild_id: guild_id guild_id: guild_id
}, },
// @ts-ignore // @ts-ignore
body body,
{ new: true }
).exec(); ).exec();
await emitEvent({ await emitEvent({

View File

@ -79,7 +79,7 @@ router.put("/:code", async (req: Request, res: Response) => {
const perms = await getPermission(req.user_id, guild_id); const perms = await getPermission(req.user_id, guild_id);
perms.hasThrow("MANAGE_GUILD"); perms.hasThrow("MANAGE_GUILD");
const template = await TemplateModel.findOneAndUpdate({ code }, { serialized_source_guild: guild }).exec(); const template = await TemplateModel.findOneAndUpdate({ code }, { serialized_source_guild: guild }, { new: true }).exec();
res.json(toObject(template)).send(); res.json(toObject(template)).send();
}); });
@ -91,7 +91,11 @@ router.patch("/:code", check(TemplateModifySchema), async (req: Request, res: Re
const perms = await getPermission(req.user_id, guild_id); const perms = await getPermission(req.user_id, guild_id);
perms.hasThrow("MANAGE_GUILD"); perms.hasThrow("MANAGE_GUILD");
const template = await TemplateModel.findOneAndUpdate({ code }, { name: req.body.name, description: req.body.description }).exec(); const template = await TemplateModel.findOneAndUpdate(
{ code },
{ name: req.body.name, description: req.body.description },
{ new: true }
).exec();
res.json(toObject(template)).send(); res.json(toObject(template)).send();
}); });

View File

@ -16,7 +16,7 @@ router.get("/:code", async (req: Request, res: Response) => {
router.post("/:code", async (req: Request, res: Response) => { router.post("/:code", async (req: Request, res: Response) => {
const { code } = req.params; const { code } = req.params;
const invite = await InviteModel.findOneAndUpdate({ code }, { $inc: { uses: 1 } }).exec(); const invite = await InviteModel.findOneAndUpdate({ code }, { $inc: { uses: 1 } }, { new: true }).exec();
if (!invite) throw new HTTPError("Unknown Invite", 404); if (!invite) throw new HTTPError("Unknown Invite", 404);
await addMember(req.user_id, invite.guild_id); await addMember(req.user_id, invite.guild_id);

View File

@ -38,7 +38,7 @@ router.patch("/", check(UserModifySchema), async (req: Request, res: Response) =
if (body.avatar) body.avatar = await handleFile(`/avatars/${req.user_id}`, body.avatar as string); if (body.avatar) body.avatar = await handleFile(`/avatars/${req.user_id}`, body.avatar as string);
if (body.banner) body.banner = await handleFile(`/banners/${req.user_id}`, body.banner as string); if (body.banner) body.banner = await handleFile(`/banners/${req.user_id}`, body.banner as string);
const user = await UserModel.findOneAndUpdate({ id: req.user_id }, body, { projection: UserUpdateProjection }).exec(); const user = await UserModel.findOneAndUpdate({ id: req.user_id }, body, { projection: UserUpdateProjection, new: true }).exec();
// TODO: dispatch user update event // TODO: dispatch user update event
res.json(toObject(user)); res.json(toObject(user));

View File

@ -151,7 +151,8 @@ export async function addRole(user_id: string, guild_id: string, role_id: string
id: user_id, id: user_id,
guild_id: guild_id guild_id: guild_id
}, },
{ $push: { roles: role_id } } { $push: { roles: role_id } },
{ new: true }
).exec(); ).exec();
if (!memberObj) throw new HTTPError("Member not found", 404); if (!memberObj) throw new HTTPError("Member not found", 404);
@ -178,7 +179,8 @@ export async function removeRole(user_id: string, guild_id: string, role_id: str
id: user_id, id: user_id,
guild_id: guild_id guild_id: guild_id
}, },
{ $pull: { roles: role_id } } { $pull: { roles: role_id } },
{ new: true }
).exec(); ).exec();
if (!memberObj) throw new HTTPError("Member not found", 404); if (!memberObj) throw new HTTPError("Member not found", 404);
@ -197,13 +199,13 @@ export async function removeRole(user_id: string, guild_id: string, role_id: str
export async function changeNickname(user_id: string, guild_id: string, nickname: string) { export async function changeNickname(user_id: string, guild_id: string, nickname: string) {
const user = await getPublicUser(user_id); const user = await getPublicUser(user_id);
var memberObj = await MemberModel.findOneAndUpdate( var memberObj = await MemberModel.findOneAndUpdate(
{ {
id: user_id, id: user_id,
guild_id: guild_id guild_id: guild_id
}, },
{ nick: nickname } { nick: nickname },
{ new: true }
).exec(); ).exec();
if (!memberObj) throw new HTTPError("Member not found", 404); if (!memberObj) throw new HTTPError("Member not found", 404);

View File

@ -157,7 +157,6 @@ export async function postHandleMessage(message: Message) {
await Promise.all([ await Promise.all([
emitEvent({ emitEvent({
event: "MESSAGE_UPDATE", event: "MESSAGE_UPDATE",
guild_id: message.guild_id,
channel_id: message.channel_id, channel_id: message.channel_id,
data data
} as MessageUpdateEvent), } as MessageUpdateEvent),
@ -172,7 +171,7 @@ export async function sendMessage(opts: Partial<Message>) {
await new MessageModel(message).populate({ path: "member", select: PublicMemberProjection }).populate("referenced_message").save() await new MessageModel(message).populate({ path: "member", select: PublicMemberProjection }).populate("referenced_message").save()
); );
await emitEvent({ event: "MESSAGE_CREATE", channel_id: opts.channel_id, data, guild_id: message.guild_id } as MessageCreateEvent); await emitEvent({ event: "MESSAGE_CREATE", channel_id: opts.channel_id, data } as MessageCreateEvent);
postHandleMessage(data).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error postHandleMessage(data).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error

3
cdn/package-lock.json generated
View File

@ -46,7 +46,8 @@
} }
}, },
"../util": { "../util": {
"version": "1.3.55", "name": "@fosscord/util",
"version": "1.0.0",
"hasInstallScript": true, "hasInstallScript": true,
"license": "GPLV3", "license": "GPLV3",
"dependencies": { "dependencies": {

View File

@ -36,7 +36,8 @@
} }
}, },
"../util": { "../util": {
"version": "1.3.55", "name": "@fosscord/util",
"version": "1.0.0",
"hasInstallScript": true, "hasInstallScript": true,
"license": "GPLV3", "license": "GPLV3",
"dependencies": { "dependencies": {

View File

@ -12,8 +12,12 @@ const connection = mongoose.createConnection(uri, {
autoIndex: true, autoIndex: true,
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
useFindAndModify: false, useFindAndModify: true,
}); });
// this will return the new updated document for findOneAndUpdate
mongoose.set("returnOriginal", false); // https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndUpdate
console.log(`[Database] connect: mongodb://${url.username}@${url.host}${url.pathname}${url.search}`); console.log(`[Database] connect: mongodb://${url.username}@${url.host}${url.pathname}${url.search}`);
connection.once("open", () => { connection.once("open", () => {
console.log("[Database] connected"); console.log("[Database] connected");