Skip to content

Commit

Permalink
Explicitly pass ObjectId to mongoose instead of relying on auto casti…
Browse files Browse the repository at this point in the history
…ng (#596)

* Explicitly pass ObjectId to mongoose instead of relying on auto casting

* Do not crash if lost connections could not be initialised
  • Loading branch information
goto-bus-stop committed Nov 30, 2023
1 parent 4238405 commit a93b0a4
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/SocketServer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { promisify } from 'node:util';
import mongoose from 'mongoose';
import lodash from 'lodash';
import sjson from 'secure-json-parse';
import { WebSocketServer } from 'ws';
Expand All @@ -14,6 +15,7 @@ import LostConnection from './sockets/LostConnection.js';
import { serializeUser } from './utils/serialize.js';

const { debounce, isEmpty } = lodash;
const { ObjectId } = mongoose.mongo;

/**
* @typedef {import('./models/index.js').User} User
Expand Down Expand Up @@ -69,7 +71,12 @@ class SocketServer {
});

uw.after(async () => {
await uw.socketServer.initLostConnections();
try {
await uw.socketServer.initLostConnections();
} catch (err) {
// No need to prevent startup for this
uw.socketServer.#logger.warn({ err }, 'could not initialise lost connections');
}
});

uw.onClose(async () => {
Expand Down Expand Up @@ -443,10 +450,14 @@ class SocketServer {
async initLostConnections() {
const { User } = this.#uw.models;
const userIDs = await this.#uw.redis.lrange('users', 0, -1);
const disconnectedIDs = userIDs.filter((userID) => !this.connection(userID));
const disconnectedIDs = userIDs
.filter((userID) => !this.connection(userID))
.map((userID) => new ObjectId(userID));

/** @type {User[]} */
const disconnectedUsers = await User.where('_id').in(disconnectedIDs);
const disconnectedUsers = await User.find({
_id: { $in: disconnectedIDs },
}).exec();
disconnectedUsers.forEach((user) => {
this.add(this.createLostConnection(user));
});
Expand Down

0 comments on commit a93b0a4

Please sign in to comment.