Skip to content

Commit

Permalink
large update
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-mirzabicer committed Jan 23, 2024
1 parent 52df45a commit 2c027bf
Show file tree
Hide file tree
Showing 22 changed files with 1,065 additions and 372 deletions.
870 changes: 668 additions & 202 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"compression": "^1.7.4",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"danfojs-node": "^1.1.2",
"dayjs": "^1.11.5",
"dotenv": "^16.0.0",
"envalid": "^7.3.1",
Expand Down Expand Up @@ -54,6 +53,7 @@
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@typescript-eslint/parser": "^5.21.0",
"bcryptjs": "^2.4.3",
"danfojs-node": "^1.1.2",
"eslint": "^8.14.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class App {
this.express.use(cors());
this.express.use(compression());
this.express.use(morgan("dev"));
this.express.use(bodyParser.urlencoded({ extended: false }));
this.express.use(bodyParser.urlencoded({ extended: true }));
this.express.use(bodyParser.json());
this.express.use(cookieParser());
this.express.use(mongoSanitize());
Expand Down
52 changes: 44 additions & 8 deletions src/controllers/post.controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import hs from "http-status";
import { postServices } from "../services/";
import stringify from "../utils/stringify";
import ApiError from "../utils/apiError";
import scheduleSave from "../utils/scheduleSave";
import { DocumentType } from "@typegoose/typegoose";
import { Request } from "express";
import { saveDocuments } from "../middlewares";

const generateScheduler = (req: Request) => (doc: DocumentType<any>) =>
scheduleSave(req, doc);

const getOne = catchAsync(async (req, res, next) => {
/**
Expand Down Expand Up @@ -35,6 +42,8 @@ const getOne = catchAsync(async (req, res, next) => {
const post = await postServices.getOne(
req.params.id,
stringify(req.query.fields),
generateScheduler(req),
true,
req.user,
multipliers //for analytics
);
Expand All @@ -43,14 +52,15 @@ const getOne = catchAsync(async (req, res, next) => {
return next(new ApiError("Not found", hs.NOT_FOUND));
}

await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { post },
});
});

const getMany = catchAsync(async (req, res, next) => {
const posts = await postServices.getMany(req.query);
const posts = await postServices.getMany(req.params);

res.status(hs.OK).json({
status: "OK",
Expand Down Expand Up @@ -91,43 +101,63 @@ const patch = catchAsync(async (req, res, next) => {
});

const like = catchAsync(async (req, res, next) => {
const post = await postServices.like(req.params.id, req.user);
const post = await postServices.like(
req.params.id,
req.user,
generateScheduler(req)
);
if (!post) {
return next(new ApiError("Not found", hs.NOT_FOUND));
}
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { post },
});
});

const save = catchAsync(async (req, res, next) => {
const post = await postServices.save(req.params.id, req.user);
const post = await postServices.save(
req.params.id,
req.user,
generateScheduler(req)
);
if (!post) {
return next(new ApiError("Not found", hs.NOT_FOUND));
}
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { post },
});
});

const unlike = catchAsync(async (req, res, next) => {
const post = await postServices.unlike(req.params.id, req.user);
const post = await postServices.unlike(
req.params.id,
req.user,
generateScheduler(req)
);
if (!post) {
return next(new ApiError("Not found", hs.NOT_FOUND));
}
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { post },
});
});

const unsave = catchAsync(async (req, res, next) => {
const post = await postServices.unsave(req.params.id, req.user);
const post = await postServices.unsave(
req.params.id,
req.user,
generateScheduler(req)
);
if (!post) {
return next(new ApiError("Not found", hs.NOT_FOUND));
}
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { post },
Expand Down Expand Up @@ -161,8 +191,10 @@ const read = catchAsync(async (req, res, next) => {
req.user,
req.body.percent,
req.body.duration,
generateScheduler(req),
req.body.leftOff
);
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { readPost },
Expand All @@ -183,8 +215,10 @@ const read = catchAsync(async (req, res, next) => {
const getNewFeed = catchAsync(async (req, res, next) => {
const posts = await postServices.getNewFeed(
req.user,
stringify(req.query.shown)
stringify(req.query.shown),
generateScheduler(req)
);
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { posts },
Expand All @@ -195,8 +229,10 @@ const getRestFeed = catchAsync(async (req, res, next) => {
if (!req.user) return next(new ApiError("Please log in", hs.UNAUTHORIZED));
const posts = await postServices.getRestFeed(
req.user._id,
stringify(req.query.shown)
stringify(req.query.shown),
generateScheduler(req)
);
await saveDocuments(req);
res.status(hs.OK).json({
status: "OK",
data: { posts },
Expand All @@ -205,7 +241,7 @@ const getRestFeed = catchAsync(async (req, res, next) => {

const finishFeed = catchAsync(async (req, res, next) => {
if (!req.user) return next(new ApiError("Please log in", hs.UNAUTHORIZED));
await postServices.finishFeed(req.user._id as string);
await postServices.finishFeed((req.user._id || req.user.id) as string);
res.status(hs.NO_CONTENT).send();
});

Expand Down
1 change: 1 addition & 0 deletions src/controllers/user.controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const getMany = catchAsync(async (req, res, next) => {
});

const getMe = catchAsync(async (req, res, next) => {
res.set("Cache-Control", "no-store");
res.status(httpStatus.OK).json({
status: "OK",
data: { user: req.user },
Expand Down
1 change: 0 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ process.on("unhandledRejection", (err: Error) => {
process.exit(1);
});
});

2 changes: 1 addition & 1 deletion src/interfaces/validation.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Validation {
public bodyForCU: Record<string, Joi.Schema>;

public queryForOne = Joi.object().keys({
fields: Joi.string(),
fields: Joi.string().optional(),
});

public getOne = {
Expand Down
82 changes: 56 additions & 26 deletions src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { UserRole } from "../constants";
import { Request, Response, NextFunction } from "express";
import passport from "passport";
import { DocumentType } from "@typegoose/typegoose";
import UserModel, {User} from "../models/user.model";
import UserModel, { User } from "../models/user.model";
import ApiError from "../utils/apiError";
import { Strategy as JwtStrategy, ExtractJwt } from "passport-jwt";

Expand All @@ -13,19 +13,20 @@ const options = {
secretOrKey: process.env.JWT_SECRET,
};

passport.use(new JwtStrategy(options, function(jwt_payload, done) {
UserModel.findOne({id: jwt_payload.sub}, function(err: any, user: any) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
passport.use(
new JwtStrategy(options, function (jwt_payload, done) {
UserModel.findById(jwt_payload.sub, function (err: any, user: any) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);

const verification =
(
Expand All @@ -49,20 +50,49 @@ const verification =
resolve();
};

// const auth =
// (...requiredRoles: UserRole[]) =>
// async (req: Request, res: Response, next: NextFunction) => {
// return new Promise((resolve, reject) => {
// passport
// .authenticate(
// "jwt",
// { session: false },
// verification(req, resolve, reject, requiredRoles)
// )(req, res, next)
// .then(() => next())
// // eslint-disable-next-line @typescript-eslint/no-explicit-any
// .catch((err: any) => next(err));
// });
// };

const auth =
(...requiredRoles: UserRole[]) =>
async (req: Request, res: Response, next: NextFunction) => {
return new Promise((resolve, reject) => {
passport
.authenticate(
"jwt",
{ session: false },
verification(req, resolve, reject, requiredRoles)
)(req, res, next)
.then(() => next())
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.catch((err: any) => next(err));
});
(req: Request, res: Response, next: NextFunction) => {
passport.authenticate(
"jwt",
// { session: false },
(err: Error, user: DocumentType<User>, info: any) => {
if (err || info || !user) {
return next(new ApiError("Unauthorized", 401));
}
req.user = user;

if (
requiredRoles.length &&
!requiredRoles.includes(user.role)
) {
return next(
new ApiError(
"You're not permitted to access this route",
403
)
);
}
// console.log(req.user);
next();
}
)(req, res, next);
};

export default auth;
17 changes: 17 additions & 0 deletions src/middlewares/document.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// import { DocumentType } from "@typegoose/typegoose";

import { Request } from "express";

const saveDocuments = async (req: Request) => {
if (req.documentsToSave) {
// req.documentsToSave.forEach(async (doc: DocumentType<any>) => {
// await doc.save();
// });
for (let i = 0; i < req.documentsToSave.length; i++) {
// console.log(req.documentsToSave[i]);
await req.documentsToSave[i].save();
}
}
};

export default saveDocuments;
1 change: 1 addition & 0 deletions src/middlewares/error.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class Handler {
error: this.error,
stack: this.error.stack,
});
console.log(this.error.stack);
return;
}
sendProd(res: Response) {
Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import errorHandler from "./error.middleware";
import validate from "./validation.middleware";
import saveDocuments from "./document.middleware";

export { errorHandler, validate };
export { errorHandler, validate, saveDocuments };
4 changes: 4 additions & 0 deletions src/middlewares/validation.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ const validate = (

const validSchema = pick(schema, ["params", "query", "body"]);

// console.log(validSchema);

//pqb = params/query/body
const pqb = pick(req, Object.keys(validSchema));

// console.log(pqb);

const { value, error } = Joi.compile(validSchema).validate(
pqb,
options
Expand Down
Loading

0 comments on commit 2c027bf

Please sign in to comment.