setting up dotenv and stuff
This commit is contained in:
@@ -1 +1,3 @@
|
||||
MONGO_CONNECTION_STRING=mongodb+srv://default:[email protected]/default?retryWrites=true&w=majority
|
||||
MONGO_CONNECTION_STRING=mongodb+srv://default:[email protected]/default?retryWrites=true&w=majority
|
||||
|
||||
JWT_TOKEN_SECRET=afajdslfwk1@lkkasdfl21ASDF!2
|
||||
@@ -0,0 +1,14 @@
|
||||
import dotenv from "dotenv";
|
||||
|
||||
if (process.env && process.env.NODE_ENV === "development") {
|
||||
dotenv.config({ path: ".env.development" });
|
||||
} else {
|
||||
dotenv.config({ path: ".env" });
|
||||
}
|
||||
|
||||
export const loadConfig = () => {
|
||||
return {
|
||||
MONGO_CONNECTION_STRING: process.env.MONGO_CONNECTION_STRING!,
|
||||
JWT_TOKEN_SECRET: process.env.JWT_TOKEN_SECRET!,
|
||||
};
|
||||
};
|
||||
@@ -6,11 +6,9 @@ import { UserService } from "./services/user.service";
|
||||
import { UserStatus } from "@nirvana/core/models";
|
||||
import { connectToDatabase } from "./services/database.service";
|
||||
import cors from "cors";
|
||||
import getContactsRoutes from "./routes/contacts";
|
||||
import getConversationRoutes from "./routes/conversation";
|
||||
import getSearchRoutes from "./routes/search";
|
||||
import getUserRoutes from "./routes/user";
|
||||
import http from "http";
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -28,7 +26,6 @@ app.get("/", (req: Request, res: Response) => {
|
||||
app.use("/api/user", getUserRoutes());
|
||||
app.use("/api/search", getSearchRoutes());
|
||||
app.use("/api/conversations", getConversationRoutes());
|
||||
app.use("/api/contacts", getContactsRoutes());
|
||||
|
||||
const PORT = 5000;
|
||||
var server = app.listen(PORT, () => console.log("express running"));
|
||||
|
||||
@@ -7,15 +7,17 @@
|
||||
"@nirvana/core": "*",
|
||||
"axios": "^0.26.1",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.0",
|
||||
"express": "^4.17.3",
|
||||
"google-auth-library": "^7.14.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mongodb": "^4.4.1",
|
||||
"socket.io": "^4.4.1"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "NODE_ENV=development && nodemon",
|
||||
"dev": "NODE_ENV=development nodemon",
|
||||
"start": "ts-node index.ts",
|
||||
"production": "NODE_ENV=production && nodemon"
|
||||
"production": "NODE_ENV=production nodemon"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.13",
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
import GetContactsResponse, {
|
||||
ContactDetails,
|
||||
} from "../../core/responses/getContacts.response";
|
||||
import Relationship, {
|
||||
RelationshipState,
|
||||
} from "@nirvana/core/models/relationship.model";
|
||||
import express, { Application, Request, Response } from "express";
|
||||
|
||||
import { ContactService } from "../services/contact.service";
|
||||
import { ObjectId } from "mongodb";
|
||||
import UpdateRelationshipStateRequest from "../../core/requests/updateRelationshipState.request";
|
||||
import { UserService } from "../services/user.service";
|
||||
import { authCheck } from "../middleware/auth";
|
||||
import { collections } from "../services/database.service";
|
||||
|
||||
export default function getContactsRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// see all of my contacts
|
||||
router.get("/", authCheck, getAllContacts);
|
||||
|
||||
// send a friend request
|
||||
router.post("/:otherUserGoogleId", authCheck, addContact);
|
||||
|
||||
router.put("/", authCheck, updateRelationshipState);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
// todo optimization with mongo lookups and such
|
||||
async function getAllContacts(req: Request, res: Response) {
|
||||
try {
|
||||
const { userId } = res.locals;
|
||||
|
||||
const resultRelationships = await ContactService.getAllUserRelationships(
|
||||
userId
|
||||
);
|
||||
|
||||
const responseObj = new GetContactsResponse();
|
||||
|
||||
// get all of the other users based on these relationships and join them
|
||||
await Promise.all(
|
||||
resultRelationships.map(async (relationship) => {
|
||||
const otherUserId =
|
||||
relationship.receiverUserId === userId
|
||||
? relationship.senderUserId
|
||||
: relationship.receiverUserId;
|
||||
|
||||
const otherUser = await UserService.getUserByGoogleId(otherUserId);
|
||||
|
||||
if (otherUser)
|
||||
responseObj.contactsDetails.push(
|
||||
new ContactDetails(otherUser, relationship)
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
res.status(200).send(responseObj);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).send(`something went wrong`);
|
||||
}
|
||||
}
|
||||
|
||||
async function addContact(req: Request, res: Response) {
|
||||
try {
|
||||
// get the userId of the person to add as a friend/contact
|
||||
const { otherUserGoogleId } = req.params;
|
||||
const { userId } = res.locals;
|
||||
|
||||
if (!otherUserGoogleId) {
|
||||
res.status(400).send("No contact id provided!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (otherUserGoogleId === userId) {
|
||||
res.status(400).send("Can't add yourself!");
|
||||
return;
|
||||
}
|
||||
|
||||
// validations
|
||||
// make sure that we are not adding a friend that already has added us
|
||||
|
||||
const newRelationship = new Relationship(
|
||||
userId,
|
||||
otherUserGoogleId,
|
||||
RelationshipState.PENDING
|
||||
);
|
||||
|
||||
const insertResult = await ContactService.createRelationship(
|
||||
newRelationship
|
||||
);
|
||||
|
||||
newRelationship._id = insertResult?.insertedId;
|
||||
|
||||
insertResult
|
||||
? res.status(200).send(newRelationship)
|
||||
: res.status(500).send("Failed to create relationship, already exists");
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).send(`something went wrong`);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateRelationshipState(req: Request, res: Response) {
|
||||
try {
|
||||
// get the userId of the person to add as a friend/contact
|
||||
const requestObj = req.body as UpdateRelationshipStateRequest;
|
||||
|
||||
const updateResult = await ContactService.updateRelationshipState(
|
||||
requestObj.relationshipId,
|
||||
requestObj.newState
|
||||
);
|
||||
|
||||
updateResult?.modifiedCount
|
||||
? res.status(200).send("Updated state of relationship")
|
||||
: res.status(500).send("Failed to update relationship");
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
res.status(500).send(`something went wrong`);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import express, { Application, Request, Response } from "express";
|
||||
|
||||
import { ContactService } from "../services/contact.service";
|
||||
import Content from "@nirvana/core/models/content.model";
|
||||
import GetConversationDetailsResponse from "@nirvana/core/responses/getConversationDetails.response";
|
||||
import { ObjectId } from "mongodb";
|
||||
@@ -15,47 +14,7 @@ export default function getConversationRoutes() {
|
||||
router.use(express.json());
|
||||
|
||||
// get data for a one on one conversation
|
||||
router.get("/:otherUserGoogleUserId", authCheck, getConversationDetails);
|
||||
// router.get("/:otherUserGoogleUserId", authCheck, getConversationDetails);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
async function getConversationDetails(req: Request, res: Response) {
|
||||
try {
|
||||
// google user Id of current user
|
||||
const { userId } = res.locals;
|
||||
const { otherUserGoogleUserId } = req.params;
|
||||
|
||||
// get the "other" user's details
|
||||
|
||||
const otherUser = await UserService.getUserByGoogleId(
|
||||
otherUserGoogleUserId
|
||||
);
|
||||
|
||||
if (!otherUser) {
|
||||
res.status(404).send("No such user found");
|
||||
return;
|
||||
}
|
||||
|
||||
// find the relationship between us...if not there just null
|
||||
const ourRelationship = await ContactService.getRelationship(
|
||||
userId,
|
||||
otherUserGoogleUserId
|
||||
);
|
||||
|
||||
// todo: get latest content based on limit count
|
||||
const latestContent: Content[] = [];
|
||||
|
||||
const resObj = new GetConversationDetailsResponse(
|
||||
otherUser,
|
||||
false,
|
||||
ourRelationship ?? undefined,
|
||||
latestContent
|
||||
);
|
||||
|
||||
res.status(200).send(resObj);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).send(`something went wrong`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { Db, ObjectId } from "mongodb";
|
||||
import Relationship, {
|
||||
RelationshipState,
|
||||
} from "@nirvana/core/models/relationship.model";
|
||||
|
||||
import { collections } from "./database.service";
|
||||
|
||||
export class ContactService {
|
||||
static async getAllUserRelationships(userId: string) {
|
||||
const query = {
|
||||
$or: [{ senderUserId: userId }, { receiverUserId: userId }],
|
||||
};
|
||||
const res = (await collections.relationships
|
||||
?.find(query)
|
||||
.toArray()) as Relationship[];
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
static async getRelationship(
|
||||
myGoogleUserId: string,
|
||||
otherGoogleUserId: string
|
||||
) {
|
||||
// i am the sender and they are the receiver
|
||||
const clauseOne = {
|
||||
$and: [
|
||||
{ senderUserId: myGoogleUserId },
|
||||
{ receiverUserId: otherGoogleUserId },
|
||||
],
|
||||
};
|
||||
// i could also be the receiver and them the sender
|
||||
const clauseTwo = {
|
||||
$and: [
|
||||
{ senderUserId: otherGoogleUserId },
|
||||
{ receiverUserId: myGoogleUserId },
|
||||
],
|
||||
};
|
||||
|
||||
const query = { $or: [clauseOne, clauseTwo] };
|
||||
const res = await collections.relationships?.findOne(query);
|
||||
|
||||
// exists
|
||||
if (res?._id) {
|
||||
return res as Relationship;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static async createRelationship(newRelationship: Relationship) {
|
||||
// i am the sender and they are the receiver
|
||||
const relationshipRes = await this.getRelationship(
|
||||
newRelationship.senderUserId,
|
||||
newRelationship.receiverUserId
|
||||
);
|
||||
|
||||
if (relationshipRes) {
|
||||
throw new Error("Already exists");
|
||||
}
|
||||
|
||||
const insertResult = await collections.relationships?.insertOne(
|
||||
newRelationship
|
||||
);
|
||||
|
||||
return insertResult;
|
||||
}
|
||||
|
||||
static async updateRelationshipState(
|
||||
relationshipId: ObjectId,
|
||||
newState: RelationshipState
|
||||
) {
|
||||
const query = { _id: new ObjectId(relationshipId) };
|
||||
const updateDoc = {
|
||||
$set: { state: newState, lastUpdatedDate: new Date() },
|
||||
};
|
||||
const result = await collections.relationships?.updateOne(query, updateDoc);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
// External Dependencies
|
||||
import * as mongoDB from "mongodb";
|
||||
// import * as dotenv from "dotenv";
|
||||
|
||||
import { loadConfig } from "../config";
|
||||
|
||||
// Global Variables
|
||||
|
||||
export const collections: {
|
||||
users?: mongoDB.Collection;
|
||||
relationships?: mongoDB.Collection;
|
||||
} = {};
|
||||
|
||||
// Initialize Connection
|
||||
export async function connectToDatabase() {
|
||||
const config = loadConfig();
|
||||
|
||||
const client: mongoDB.MongoClient = new mongoDB.MongoClient(
|
||||
"mongodb+srv://default:[email protected]/default?retryWrites=true&w=majority"
|
||||
config.MONGO_CONNECTION_STRING
|
||||
);
|
||||
|
||||
await client.connect();
|
||||
@@ -20,11 +21,8 @@ export async function connectToDatabase() {
|
||||
const db: mongoDB.Db = client.db(process.env.DB_NAME);
|
||||
|
||||
const usersCollection: mongoDB.Collection = db.collection("users");
|
||||
const relationshipCollection: mongoDB.Collection =
|
||||
db.collection("relationships");
|
||||
|
||||
collections.users = usersCollection;
|
||||
collections.relationships = relationshipCollection;
|
||||
|
||||
console.log(
|
||||
`Successfully connected to database: ${db.databaseName} and collections`
|
||||
|
||||
Reference in New Issue
Block a user