trying to add everything but models are messy with mongoose...just nonsense from higher perspective

This commit is contained in:
talksik
2022-04-01 12:28:09 -04:00
parent ce0fb7a885
commit 5f5d977012
12 changed files with 194 additions and 128 deletions
+17 -16
View File
@@ -3,8 +3,7 @@ import express, { Application, Request, Response } from "express";
import { NextFunction } from "express";
import SocketChannels from "@nirvana/core/sockets/channels";
import { UserService } from "./services/user.service";
import { UserStatus } from "@nirvana/core/models";
import { connectToDatabase } from "./services/database.service";
import { UserStatus } from "@nirvana/core/models/user.model";
import cors from "cors";
import getConversationRoutes from "./routes/conversation";
import getSearchRoutes from "./routes/search";
@@ -29,7 +28,6 @@ app.use("/api/conversations", getConversationRoutes());
const PORT = 5000;
var server = app.listen(PORT, () => console.log("express running"));
connectToDatabase();
// socket IO stuff
@@ -106,22 +104,25 @@ io.on("connection", function (socket: any) {
async (userGoogleId: string, newStatus: UserStatus) => {
console.log("new status for user");
const resultUpdate = await UserService.updateUserStatus(
userGoogleId,
newStatus
);
// todo persist status changes
// const resultUpdate = await UserService.updateUserStatus(
// userGoogleId,
// newStatus
// );
// tell all rooms that the user is part of
// that this user has updated their status
if (resultUpdate?.modifiedCount) {
socket.rooms.forEach((roomId: string) => {
io.in(roomId).emit(
SocketChannels.SEND_USER_STATUS_UPDATE,
userGoogleId,
newStatus
);
});
}
// if (resultUpdate?.modifiedCount) {
// }
socket.rooms.forEach((roomId: string) => {
io.in(roomId).emit(
SocketChannels.SEND_USER_STATUS_UPDATE,
userGoogleId,
newStatus
);
});
}
);
+1
View File
@@ -12,6 +12,7 @@
"google-auth-library": "^7.14.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^4.4.1",
"mongoose": "^6.2.9",
"socket.io": "^4.4.1"
},
"scripts": {
-1
View File
@@ -6,7 +6,6 @@ import { ObjectId } from "mongodb";
import Relationship from "@nirvana/core/models/relationship.model";
import { UserService } from "../services/user.service";
import { authCheck } from "../middleware/auth";
import { collections } from "../services/database.service";
export default function getConversationRoutes() {
const router = express.Router();
+19 -20
View File
@@ -1,7 +1,6 @@
import express, { Application, Request, Response } from "express";
import SearchResponse from "@nirvana/core/responses/search.response";
import { User } from "@nirvana/core/models";
import { UserService } from "../services/user.service";
import { authCheck } from "../middleware/auth";
@@ -11,30 +10,30 @@ export default function getSearchRoutes() {
router.use(express.json());
// get user details based on id token
router.get("/", authCheck, handleSearch);
// router.get("/", authCheck, handleSearch);
return router;
}
async function handleSearch(req: Request, res: Response) {
try {
const { query } = req.query;
// async function handleSearch(req: Request, res: Response) {
// try {
// const { query } = req.query;
if (!query) {
res.status(400).send("No search query provided!");
return;
}
// if (!query) {
// res.status(400).send("No search query provided!");
// return;
// }
// text search on users
const users: User[] | null = await UserService.getUsersLikeEmailAndName(
query as string
);
// // text search on users
// const users: User[] | null = await UserService.getUsersLikeEmailAndName(
// query as string
// );
const resObj = new SearchResponse(users ?? []);
// const resObj = new SearchResponse(users ?? []);
res.send(resObj);
} catch (error) {
console.log(error);
res.status(500).send(`something went wrong`);
}
}
// res.send(resObj);
// } catch (error) {
// console.log(error);
// res.status(500).send(`something went wrong`);
// }
// }
+2 -4
View File
@@ -1,13 +1,13 @@
import { GoogleUserInfo, User } from "@nirvana/core/models";
import express, { Application, Request, Response } from "express";
import GoogleUserInfo from "@nirvana/core/models/googleUserInfo.model";
import { OAuth2Client } from "google-auth-library";
import { ObjectID } from "bson";
import { ObjectId } from "mongodb";
import { User } from "@nirvana/core/models/user.model";
import { UserService } from "../services/user.service";
import { UserStatus } from "../../core/models/user.model";
import { authCheck } from "../middleware/auth";
import { collections } from "../services/database.service";
const client = new OAuth2Client(
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com"
@@ -83,8 +83,6 @@ async function login(req: Request, res: Response) {
// create user if not exists
const insertResult = await UserService.createUserIfNotExists(newUser);
newUser._id = insertResult?.insertedId;
// create jwt token with new user info
insertResult
+31 -19
View File
@@ -1,30 +1,42 @@
// External Dependencies
import * as mongoDB from "mongodb";
import { loadConfig } from "../config";
import { IUser, UserStatus } from "@nirvana/core/models/user.model";
// Global Variables
export const collections: {
users?: mongoDB.Collection;
} = {};
import { ObjectId } from "mongodb";
import { loadConfig } from "../config";
import mongoose from "mongoose";
connectToDatabase().catch((err) => console.log(err));
// Initialize Connection
export async function connectToDatabase() {
const config = loadConfig();
const client: mongoDB.MongoClient = new mongoDB.MongoClient(
config.MONGO_CONNECTION_STRING
);
await mongoose.connect(config.MONGO_CONNECTION_STRING);
await client.connect();
const db: mongoDB.Db = client.db(process.env.DB_NAME);
const usersCollection: mongoDB.Collection = db.collection("users");
collections.users = usersCollection;
console.log(
`Successfully connected to database: ${db.databaseName} and collections`
);
console.log(`Successfully connected to mongoose/mongodb`);
}
const userSchema = new mongoose.Schema<IUser>(
{
name: { type: String, required: true },
email: { type: String, required: true },
googleId: { type: String, required: true }, // our Google id that every google user has unique that we are going to use for now
verifiedEmail: Boolean,
givenName: { type: String, required: true },
familyName: { type: String, required: true },
picture: String,
locale: String,
// additional properties specific to our users collection
createdDate: Date,
status: String,
lastUpdatedDate: Date,
_id: ObjectId,
},
{ collection: "users" }
);
export const UserModel = mongoose.model<IUser>("User", userSchema);
+41 -55
View File
@@ -1,70 +1,56 @@
import { GoogleUserInfo, User } from "@nirvana/core/models";
import GoogleUserInfo from "../../core/models/googleUserInfo.model";
import { ObjectId } from "mongodb";
import { User } from "@nirvana/core/models/user.model";
import { UserModel } from "./database.service";
import { UserStatus } from "../../core/models/user.model";
import axios from "axios";
import { collections } from "./database.service";
export class UserService {
static async getUserByGoogleId(userId: string) {
const query = { googleId: userId };
const res = await collections.users?.findOne(query);
// exists
if (res?._id) {
return res as User;
}
return null;
}
static async getUserByEmail(email: string) {
const query = { email };
const res = await collections.users?.findOne(query);
const res = await UserModel.findOne({ email });
// exists
if (res?._id) {
return res as User;
if (!res?.$isEmpty) {
return res;
}
return null;
}
static async getUsersLikeEmailAndName(searchQuery: string) {
// based on index defined in Mongo atlas
const query = {
$search: {
index: "default",
text: {
query: searchQuery,
path: {
wildcard: "*",
},
},
},
};
// static async getUsersLikeEmailAndName(searchQuery: string) {
// // based on index defined in Mongo atlas
// const query = {
// $search: {
// index: "default",
// text: {
// query: searchQuery,
// path: {
// wildcard: "*",
// },
// },
// },
// };
// const res = await collections.users?.find(query).toArray();
// // const res = await collections.users?.find(query).toArray();
const res = await collections.users?.aggregate([query]).toArray();
// const res = await collections.users?.aggregate([query]).toArray();
// exists
if (res?.length) {
return res as User[];
}
// // exists
// if (res?.length) {
// return res as User[];
// }
return null;
}
// return null;
// }
static async createUserIfNotExists(newUser: User) {
const exists = (
await collections.users?.findOne({ googleId: newUser.googleId })
)?._id;
const getUser = await this.getUserByEmail(newUser.email);
if (!exists) {
return await collections.users?.insertOne(newUser);
if (!getUser) {
const newUser = new UserModel(User);
newUser.isNew = true;
return newUser.save();
}
// user with email exists already, don't create
@@ -81,14 +67,14 @@ export class UserService {
).data;
}
static async updateUserStatus(userGoogleId: string, newStatus: UserStatus) {
const query = { googleId: userGoogleId };
const updateDoc = {
$set: { status: newStatus, lastUpdatedDate: new Date() },
};
// static async updateUserStatus(userId: string, newStatus: UserStatus) {
// const query = { googleId: userGoogleId };
// const updateDoc = {
// $set: { status: newStatus, lastUpdatedDate: new Date() },
// };
const resultUpdate = await collections.users?.updateOne(query, updateDoc);
// const resultUpdate = UserModel.findByIdAndUpdate
return resultUpdate;
}
// return resultUpdate;
// }
}