Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Config/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ config({
path: '.env'
});

export const {DB_URI,PORT,JWT_EXPIRES_IN,JWT_SECRET,ARCJET_KEY} = process.env;
export const {DB_URI,TEST_DB_URI,PORT,JWT_EXPIRES_IN,JWT_SECRET,ARCJET_KEY,NODE_ENV} = process.env;
17 changes: 12 additions & 5 deletions Controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@ import jwt from "jsonwebtoken";
import { JWT_EXPIRES_IN, JWT_SECRET } from "../Config/env.js";

export const signUp = async (req, res, next) => {

const session = await mongoose.startSession();
session.startTransaction();

if (process.env.NODE_ENV !== "test") {
session.startTransaction();
}


try {
const { name, email, password } = req.body;
Expand Down Expand Up @@ -51,10 +56,12 @@ export const signUp = async (req, res, next) => {
});

} catch (error) {
await session.abortTransaction();
session.endSession();
console.error("Signup Error:", error.message);
next(error);

if (process.env.NODE_ENV !== "test") {
await session.abortTransaction();
await session.endSession();
}

}
};

Expand Down
67 changes: 67 additions & 0 deletions Controllers/subscription.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import subSchema from "../models/subscription.model.js";
import Subscription from "../models/subscription.model.js";

export const createSubscriptions=async(req,res,next)=>{

try{
const newSubscription=await subSchema.create({
...req.body,
user:req.user._id
})

res.status(201).json({
status:"success",
data:newSubscription
});

}
catch(err){
next(err);
}

}

export const getSpecificUserSubscription=async(req,res,next)=>{

try{

if(req.user.id!=req.params.id){

const error=new Error("Access denied");
res.status(401);
throw error;

}

const theirSubs=await Subscription.find({
user:req.params.id
})

res.status(200).json({
status:"success",
data:theirSubs
})
}
catch(err){
next(err);
}
}

export const getAllSubscriptions=async(req,res,next)=>{

try{

const allSubs=await Subscription.find({

});

res.status(200).json({
status:"success",
data:allSubs
})


}catch(err){
next(err);
}
}
36 changes: 22 additions & 14 deletions DB/mongodb.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import mongoose from 'mongoose';
import mongoose from "mongoose";
import { DB_URI, TEST_DB_URI, NODE_ENV } from "../Config/env.js";

import {DB_URI} from "../Config/env.js";
const connectToDatabase = async () => {

if(!DB_URI){
throw new Error('MongoDB URI doesn\'t exist');
}
if (process.env.NODE_ENV === "test") {
console.log("🧪 Using in-memory MongoDB (no real connection).");
return; // don't connect to real Mongo in tests
}

const connectToDbFunction=async()=>{
try {
await mongoose.connect(DB_URI);
console.log("MongoDB Connected!");
}catch (error){
console.error(error);
}
}

try {
const uri = DB_URI;
console.log("🔗 Connecting to the real db:", uri);

export default connectToDbFunction;
await mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

} catch (error) {
console.error("❌ DB connection failed:", error);
if (NODE_ENV !== "test") process.exit(1); // avoid killing Jest
}
};

export default connectToDatabase;
1 change: 1 addition & 0 deletions Middlewares/auth.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { JWT_SECRET } from "../Config/env.js";
import User from "../Models/user.model.js";

const authorize = async (req, res, next) => {

try {
// 1️⃣ Extract token from headers
let token;
Expand Down
3 changes: 2 additions & 1 deletion Models/subscription.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ const subSchema = new mongoose.Schema({
timeStamps: true
})

const Subscription=new mongoose.model('User',subSchema);
const Subscription=new mongoose.model('Subscription',subSchema);
//create and stores subscriptions in subscriptions collection

export default Subscription;
33 changes: 18 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@

import express from "express";
import {PORT} from "./Config/env.js";
import { PORT, NODE_ENV } from "./Config/env.js";
import connectToDatabase from "./DB/mongodb.js";
import errorHandler from "./Middlewares/error.middleware.js";
import arcjetMiddleware from "./Middlewares/arcjet.middleware.js";
import authorize from "./Middlewares/auth.middleware.js";

const app = express();


import authRoutes from "./routes/auth.routes.js";
import subscriptionRoutes from "./routes/subscription.routes.js";
import userRoutes from "./routes/user.routes.js";
import authMiddleware from "./Middlewares/auth.middleware.js";

app.use(express.json());

app.use("/api/v1/auth",authRoutes); //go to api/v1/auth endpoint for authRoutes
app.use("/api/v1/subscriptions",subscriptionRoutes);
app.use("/api/v1/users",userRoutes);
app.use(errorHandler);
app.use(arcjetMiddleware);
app.use("/api/v1/auth", authRoutes);
app.use("/api/v1/subscriptions", subscriptionRoutes);
app.use("/api/v1/users", userRoutes);


app.use(errorHandler);
//app.use(arcjetMiddleware);
app.use(authorize);

app.get("/", (req, res) => {
res.send("HELLO FROM THE SERVER");
})

app.listen(PORT,async()=>{
console.log(`Server running on port ${PORT}`);

await connectToDatabase();
})
});

if (process.env.NODE_ENV !== "test") {
connectToDatabase().then(() => {
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`));
});
}

export { app, connectToDatabase };
export default app;

66 changes: 66 additions & 0 deletions app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// process.env.NODE_ENV = "test";
//
// import mongoose from "mongoose";
// import request from "supertest";
// import { MongoMemoryServer } from "mongodb-memory-server";
// import app from './app.js'
// import User from "./Models/user.model.js";
// import {afterAll, beforeAll, beforeEach, describe, expect, it} from "@jest/globals";
//
//
//
// let mongoServer;
//
// beforeAll(async () => {
//
// mongoServer = await MongoMemoryServer.create();
// const uri = mongoServer.getUri();
//
// if (mongoose.connection.readyState !== 0) {
// await mongoose.disconnect();
// }
//
// await mongoose.connect(uri, {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// });
// });
//
// afterAll(async () => {
// await mongoose.connection.dropDatabase();
// await mongoose.connection.close();
// await mongoServer.stop();
// });
//
// describe("Checking the sign-up POST api with SuperTest", () => {
//
//
//
// it("should create account successfully with correct credentials", async () => {
// const res = await request(app).post("/api/v1/auth/sign-up").send(
// { name:"Nandul",
// email: "nandulhissella@gmail.com",
// password: "Inandul24$"
// });
//
// expect(res.status).toBe(201);
// expect(res.body.message).toBe("User created successfully");
// });
//
// it("should fail with missing fields", async () => {
// const res = await request(app)
// .post("/api/v1/auth/sign-up")
// .send({ email: "nandulhissella@gmail.com", password: "dummypwd" });
//
// expect(res.status).toBe(400);
//
// });
//
// it("should fail if email is duplicated", async () => {
// const res = await request(app)
// .post("/api/v1/auth/sign-in")
// .send({ email: "test@test.com", password: "123456", name:"Dummy user" });
//
// expect(res.status).toBe(409);
// });
// });
4 changes: 0 additions & 4 deletions jest.config.js

This file was deleted.

6 changes: 6 additions & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.mjs"],
transform: {}, // disable Babel transform since we use native ESM
extensionsToTreatAsEsm: [".js"], // make Jest treat .js files as ESM
};
19 changes: 19 additions & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";

let mongo;

beforeAll(async () => {
mongo = await MongoMemoryServer.create();
const uri = mongo.getUri();
await mongoose.connect(uri);
});

afterEach(async () => {
await mongoose.connection.db.dropDatabase();
});

afterAll(async () => {
await mongoose.connection.close();
await mongo.stop();
});
Loading
Loading