There are two routes in my code that perform the same operation on a token to extract a user document from the database. Subsequently, each route carries out unique operations on this extracted document. In an effort to streamline the code, I am attempting to create a function that handles this common part of the operation and then call it within both routes. Here's a snippet of what I have in mind:
let user = await returnUser(req, res, token)
user.verified = true;
await user.save();
However, I am facing an issue due to the fact that I am using Typescript. Specifically, I am encountering type errors when trying to access methods like user.save() or properties within the document. Can someone provide guidance on how to properly set up typings so that I can work with the returned document from the function without encountering these type errors?
Additional context: Below is the actual code snippet for the function that retrieves the user document:
import { Request, Response } from "express";
import { Token } from "../util/token";
import { User } from "../models/user";
export const returnUser = async (
req: Request,
res: Response,
token: string
) => {
if (!token) return res.status(400).send({ error: "Token is not present" });
let decoded = await Token.decode(token);
if (decoded === false) {
return res.status(400).send({ error: "Invalid Token" });
}
let email = decoded.email;
let user = await User.findOne({ email });
if (!user) return res.status(400).send({ error: "User not found" });
if (user.createdAt.getTime() !== decoded.epoch)
return res.status(400).send({ error: "Invalid timestamp" });
return user;
};
In addition, here is the link to the specific error that is being triggered:
Message when hovering over the error
And finally, here is the interface definition for 'UserDoc' which represents the structure of my user documents:
interface UserDoc extends mongoose.Document {
email: string;
username: string | null;
verified: boolean;
createdAt: Date;
}