Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

base app setup #1

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules
.env
npm-debug.log
.DS_Store
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Game Labs
20 changes: 20 additions & 0 deletions db.connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require("mongoose");

const uri = process.env.GAME_LABS_DB_URI;

const initDBConnection = async () => {
try{
await mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
console.log("DB connection successful");
}
catch(error){
console.log("Error connecting to DB\nLogs - ");
console.error(error);
}
}

module.exports = { initDBConnection };
91 changes: 91 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
require("dotenv").config();

const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const { initDBConnection } = require("./db.connect");
const { requestInfo, errorHandler } = require("./middleware/middleware");

const { User } = require("./models/user.model");

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(requestInfo);

initDBConnection();

const usersRouter = require("./routers/users.router");
app.use("/users", usersRouter);

const userFixedPlaylists = require("./routers/user-fixed-playlists.router");
app.use("/user-fixed-playlists", userFixedPlaylists);

const playlistsRouter = require("./routers/playlists.router");
app.use("/playlists", playlistsRouter);

const videosRouter = require("./routers/videos.router");
app.use("/videos", videosRouter);

const categoriesRouter = require("./routers/categories.router");
app.use("/categories", categoriesRouter);

app.get("/", (req, res) => {
res.send("Connected to Game LABS server");
});

app.post("/login", async (req, res) => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can make a separate route for login along with others.

const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.json({
success: false,
message: "Email not found",
errorMessage: "Email not found",
});
}
const validPassword = await bcrypt.compare(password, user.password);

if (validPassword) {
const token = jwt.sign(
{ userId: user._id, email: user.email },
process.env.JWT_SECRET
);
res.json({
success: true,
message: "Login success",
user: {
id: user._id,
name: user.name,
email: user.email,
role: user.role,
},
token,
});
} else {
res.json({ success: false, message: "Invalid password" });
}
} catch (error) {
res.status(400).json({
success: false,
message: "User not found",
errorMessage: error.message,
});
}
});

// catching errors
app.use(errorHandler);

// 404 Handler
app.use((req, res) => {
res.status(404).json({ success: false, message: "Route not found" });
});

const PORT = process.env.PORT || 5050;
app.listen(PORT, () => {
console.log("SERVER STARTED on port: ", PORT);
});
48 changes: 48 additions & 0 deletions middleware/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const jwt = require("jsonwebtoken");

const requestInfo = (req, res, next) => {
console.log("\nREQUEST", req.path);
console.log("METHOD", req.method);
next();
};

const paramLogger = (req, res, next) => {
if (req.params) {
console.log("\nPARAMS");
console.table(req.params);
req.paramsChecked = true;
} else {
req.paramsChecked = false;
}
next();
};

const authVerify = (req, res, next) => {
const token = req.headers.authorization;
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userAuth = { userId: decoded.userId, email: decoded.email };
if(req.user && decoded.userId !== String(req.user._id)){
return res.status(401).json({
success: false,
message: "User authentication failed",
});
}
return next();
} catch (error) {
return res.status(401).json({
success: false,
message: "Unauthorised access, put valid token",
});
}
};

const errorHandler = (err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
message: "error occurred, see the error message for more details",
});
};

module.exports = { requestInfo, paramLogger, errorHandler, authVerify };
57 changes: 57 additions & 0 deletions models/category.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const mongoose = require("mongoose");
require('mongoose-type-url');

const CategorySchema = new mongoose.Schema(
{
name: {
type: String,
required: "Cannot create a category without a `name` field"
},
developers: [
{
type: String,
required: "Provide atleat one developer, expected an array"
}
],
publishers: [
{
type: String,
required: "Provide atleat one publisher, expected an array"
}
],
release: {
type: Date
},
genre: [
{type: String}
],
thumbnail: {
type: mongoose.SchemaTypes.Url,
required: "Category needs a thumbnail image"
},
icon: {
type: mongoose.SchemaTypes.Url,
required: "Category needs an icon"
},
gallery: [
{type: mongoose.SchemaTypes.Url}
],
description: {
type: String,
minLength: [100, "Description should be atleast 100 characters long"]
},
platforms: [
{
type: String,
enum: ["PS4", "PS5", "Xbox One | X", "Xbox Series X | S", "Windows 10", "macOS", "iOS", "Android", "Nintendo Switch"],
}
]
},
{
timestamps: true
}
);

const Category = mongoose.model("Category", CategorySchema);

module.exports = { Category };
22 changes: 22 additions & 0 deletions models/playlist.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require("mongoose");

const PlaylistSchema = new mongoose.Schema(
{
title: {
type: String,
required: "Cannot create a playlist without a `title`"
},
videos: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Video",
required: true
}]
},
{
timestamps: true
}
);

const Playlist = mongoose.model("Playlist", PlaylistSchema);

module.exports = { Playlist };
64 changes: 64 additions & 0 deletions models/user.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const mongoose = require("mongoose");
require("mongoose-type-url");

const UserSchema = new mongoose.Schema(
{
name: {
type: String,
required: "Cannot create a user without a `name`",
},
email: {
type: String,
required: "Email address is required",
unique: true,
index: true,
validate: [
(email) => {
let re = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/);
return re.test(email);
},
"Provide a valid email address",
],
},
password: {
type: String,
required: true,
minLength: [8, "Password must be atleast 8 characters long"],
},
role: {
type: String,
enum: ["user", "admin"],
default: "user",
},
profileImage: {
type: mongoose.SchemaTypes.Url,
},
categorySubscriptions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
},
],
playlists: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Playlist",
},
],
history: {
type: mongoose.Schema.Types.ObjectId,
ref: "Playlist",
},
watchLater: {
type: mongoose.Schema.Types.ObjectId,
ref: "Playlist",
},
},
{
timestamps: true,
}
);

const User = mongoose.model("User", UserSchema);

module.exports = { User };
44 changes: 44 additions & 0 deletions models/video.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const mongoose = require("mongoose");
require('mongoose-type-url');

const VideoSchema = new mongoose.Schema(
{
title: {
type: String,
required: "Cannot create a playlist without a `name`"
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
required: true
},
thumbnail: {
type: mongoose.SchemaTypes.Url,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct me if I'm wrong, but type: "String" would also work here ?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want thumbnail to be specifically a url for the image, hence used that type

required: "Video needs a thumbnail image url"
},
video: {
type: mongoose.SchemaTypes.Url,
required: "Video needs a url"
},
description: {
type: String
},
runtime: {
minutes: {
type: Number,
required: "Video runtime - minutes required"
},
seconds: {
type: Number,
required: "Video runtime - seconds required"
}
}
},
{
timestamps: true
}
);

const Video = mongoose.model("Video", VideoSchema);

module.exports = { Video };
Loading