Skip to content

Development #27

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

Merged
merged 2 commits into from
Jul 26, 2023
Merged
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
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<img src="https://github.com/yamilt351/api-rest/assets/88646148/6fa7be51-ea03-4be7-9f31-3b6365e68f46" width="100" height="100" align="center">



# INDEX
- [About this project](#About-this-project)
- [Development Environment Setup](#Development-Environment-Setup)
Expand Down Expand Up @@ -45,6 +44,15 @@ STRIPE_TOKEN=sk_text_YourStripeToken

```

```
SECRET:your_google_oauth_secret
```

```
CLIENTID:your_google_oauth_cliendId
```


- Start the application using `npm run dev` or `yarn run dev` to launch the application.
- Access the application in a web browser using the provided URL or port number.

Expand All @@ -55,12 +63,20 @@ STRIPE_TOKEN=sk_text_YourStripeToken
## Tests

- The aplication was tested with [Jest](https://jestjs.io/) and [Supertest](https://www.npmjs.com/package/supertest)

```
npm test
npm run test

```

# Live demo & Product Explanation.

[Demo](https://ciervademo.onrender.com/)
This a simple demo.
Shoping Cart State is hanlde by the frontend, so you can store the shoping cart items init and still keep it even if the user is not loged into the app.
This guarantee an excelent user experience btw, bc the user can explore your site before making orders.
The backend provide pagination for some routes, for more info [check the Documentation](https://documenter.getpostman.com/view/21643141/2s93sXcaLf#f3eb5112-676b-46c6-89a2-f5dd6b6c0927)


# Contribution.

- Read The Documentation
Expand Down
12 changes: 5 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import express from 'express';
import importMiddlewares from './middlewaresHandler.js';
import { connect } from './server.js';
import { config } from 'dotenv';
import importMiddlewares from './server/config/middlewaresConfig.js';
import { connect } from './server/config/serverConfig.js';
import { errorHandler } from './server/helpers/errorHandler.js';
import apiRouthes from './server/api/routes.js';
import apiRouthes from './server/config/endpointsConfig.js';
import envConfig from './server/config/envConfig.js';

//config

config();
const app = express();
const PORT = process.env.PORT;
export const JWT_TOKEN = process.env.JWT_TOKEN;
export const JWT_TOKEN = envConfig.JWT;

// importing middlewares
const middlewares = await importMiddlewares();
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "node index.js",
"dev": "nodemon index.js"
},
Expand Down
16 changes: 0 additions & 16 deletions server/api/routes.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Comment from './commentModel.js';
import commentService from './commentService.js';
// function to check ownership
import isResourceOwner from '../helpers/isOwner.js';
import isResourceOwner from '../../helpers/isOwner.js';

const commentController = {
createComment,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import commentController from './commentController.js';
import express from 'express';
import { cleanBody } from '../helpers/sanitizer.js';
import authMiddleware from '../helpers/jwt.js';
import { cleanBody } from '../../helpers/sanitizer.js';
import authMiddleware from '../../helpers/jwt.js';
const router = express.Router();

router.post(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Router } from 'express';
import authMiddleware from '../helpers/jwt.js';
import adminCheck from '../helpers/adminCheck.js';
import authMiddleware from '../../helpers/jwt.js';
import adminCheck from '../../helpers/adminCheck.js';
import { caching } from '../../helpers/cache.js';
import { cleanBody, validateQuery } from '../../helpers/sanitizer.js';
import productController from './productController.js';
import { caching } from '../helpers/cache.js';
import { cleanBody, validateQuery } from '../helpers/sanitizer.js';

const router = Router();

Expand Down Expand Up @@ -51,4 +51,4 @@ router.delete(
cleanBody,
productController.deleteProduct,
);
export default router;
export default router;
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Product from './productModel.js';
import mongoose from 'mongoose';
import { NotFoundError } from '../helpers/errorHandler.js';
import { NotFoundError } from '../../helpers/errorHandler.js';

const productService = {
getProduct,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Router } from 'express';
import purchaseController from './purchasesController.js';
import authMiddleware from '../helpers/jwt.js';
import adminCheck from '../helpers/adminCheck.js';
import authMiddleware from '../../helpers/jwt.js';
import adminCheck from '../../helpers/adminCheck.js';
const router = Router();

router.post('/create', authMiddleware, purchaseController.createPurchase);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Purchase from './purchasesModel.js';
import StripePaymentProvider from '../helpers/stripe.js';
import StripePaymentProvider from '../../helpers/stripe.js';
const paymentProvider = new StripePaymentProvider();

const purchaseService = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import responseService from './responsesService.js';
import Response from './responsesModel.js';
// function to check ownership
import isResourceOwner from '../helpers/isOwner.js';
import isResourceOwner from '../../helpers/isOwner.js';

const responseControllers = {
createResponse,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import responseControllers from './responsesController.js';
import express from 'express';
import { cleanBody } from '../helpers/sanitizer.js';
import authMiddleware from '../helpers/jwt.js';
import { cleanBody } from '../../helpers/sanitizer.js';
import authMiddleware from '../../helpers/jwt.js';
const router = express.Router();
router.get('/getAll', authMiddleware, responseControllers.getAllResponse);
router.post(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import cartService from './shopingCartService.js';
// function to check ownership
import isResourceOwner from '../helpers/isOwner.js';
import Cart from '../ShopingCart/shopinCartModel.js';
import isResourceOwner from '../../helpers/isOwner.js';
import Cart from './shopinCartModel.js';

const cartController = {
createCart,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ShoppingCart from './shopinCartModel.js';
import userService from '../Users/usersService.js';
import userService from '../users/usersService.js';

const cartService = {
createCart,
editCart,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Router } from 'express';
import cartController from './shopingCartController.js';
import authMiddleware from '../helpers/jwt.js';
import adminCheck from '../helpers/adminCheck.js';
import { cleanBody } from '../helpers/sanitizer.js';
import authMiddleware from '../../helpers/jwt.js';
import adminCheck from '../../helpers/adminCheck.js';
import { cleanBody } from '../../helpers/sanitizer.js';
const router = Router();

router.post('/create', authMiddleware, cleanBody, cartController.createCart);
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Router } from 'express';
import usersController from './usersControllers.js';
import adminCheck from '../helpers/adminCheck.js';
import authMiddleware from '../helpers/jwt.js';
import { cleanBody } from '../helpers/sanitizer.js';
import adminCheck from '../../helpers/adminCheck.js'
import authMiddleware from '../../helpers/jwt.js';
import { cleanBody } from '../../helpers/sanitizer.js';
const router = Router();

router.post('/signIn', cleanBody, usersController.signIn);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import userService from './usersService.js';
const maxAge = 24 * 60 * 60 * 1000;

const usersController = {
signIn,
signUp,
getUser,
getStat,
googleToken,
findByEmail,
};

function signIn(req, res, next) {
console.log("aca");
console.log('aca');
userService
.signIn(req.body)
.then(({ user, sendToken }) => {
Expand All @@ -31,6 +22,7 @@ console.log("aca");
}

function signUp(req, res, next) {
console.log('controller');
userService
.signUp(req.body)
.then((user) => res.json(user))
Expand Down Expand Up @@ -65,4 +57,12 @@ function googleToken(req, res, next) {
.catch((error) => next(error));
}

const usersController = {
signIn,
signUp,
getUser,
getStat,
googleToken,
findByEmail,
};
export default usersController;
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import Encrypt from '../helpers/bcrypt.js';
import User from './userModel.js';
import { JWT_TOKEN } from '../../index.js';
import Token from '../helpers/token.js';
import { JWT_TOKEN } from '../../../index.js';
import Token from '../../helpers/token.js';
import Encrypt from '../../helpers/bcrypt.js';
import {
BadRequestError,
NotFoundError,
UnauthorizedError,
} from '../helpers/errorHandler.js';
} from '../../helpers/errorHandler.js';
import { OAuth2Client } from 'google-auth-library';
const SECRET = process.env.SECRET;
const CLIENTID = process.env.CLIENTID;
import envConfig from '../../config/envConfig.js';

const SECRET = envConfig.SECRET;
const CLIENTID = envConfig.CLIENTID;

//config
const userService = {
Expand All @@ -31,7 +33,7 @@ async function findByEmail(email) {
if (alreadyExist) {
return alreadyExist;
} else {
return null;
throw new NotFoundError(`user with ${email} not found`);
}
}

Expand Down Expand Up @@ -64,22 +66,21 @@ async function checkLength(item, num) {

async function signUp(user) {
const allowedFields = ['email', 'password', 'username'];

const filteredUser = Object.keys(user) //check if user contains allowedFields
.filter((key) => allowedFields.includes(key))
.reduce((obj, key) => {
obj[key] = user[key];
return obj;
}, {});
await checkLength(filteredUser.password, 8);

const validatePass = await checkLength(filteredUser.password, 8);
if (validatePass) {
try {
const encryptPassword = await encrypt.hashPassword(filteredUser.password);
const createUser = new User({ ...filteredUser, password: encryptPassword });
const newUser = await createUser.save();
return newUser;
} else {
throw new BadRequestError('password does not match');
} catch (error) {
throw new BadRequestError(error.message);
}
}

Expand Down
16 changes: 16 additions & 0 deletions server/config/endpointsConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import user from '../application/users/userRoutes.js';
import cart from '../application/shopingCart/shoppingCartRoutes.js';
import product from '../application/products/productRoutes.js';
import purchase from '../application/purchases/purchasesRoutes.js';
import comment from '../application/comments/commentsRoutes.js';
import response from '../application/responses/responsesRoutes.js';

const apiRouthes = [
{ route: '/api/users', controller: user },
{ route: '/api/carts', controller: cart },
{ route: '/api/purchases', controller: purchase },
{ route: '/api/products', controller: product },
{ route: '/api/comments', controller: comment },
{ route: '/api/responses', controller: response },
];
export default apiRouthes
12 changes: 12 additions & 0 deletions server/config/envConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { config } from 'dotenv';
config();

const envConfig = {
PORT: process.env.PORT,
JWT: process.env.JWT_TOKEN,
SERVER: process.env.MONGO,
STRIPE: process.env.STRIPE_TOKEN,
SECRET: process.env.SECRET,
CLIENTID: process.env.CLIENTID,
};
export default envConfig;
4 changes: 2 additions & 2 deletions middlewaresHandler.js → server/config/middlewaresConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

//middleware Files
const middlewareDir = path.join(__dirname, 'server/middlewares');
const middlewareDir = path.join(__dirname, '../middlewares');

//put the middleware files into the array & export it
const importMiddlewares = async () => {
Expand All @@ -14,7 +14,7 @@ const importMiddlewares = async () => {

for (const file of middlewareFiles) {
console.log(`./server/middlewares/${file}`);
const middleware = await import(`./server/middlewares/${file}`);
const middleware = await import(`../middlewares/${file}`);
middlewareArray.push(middleware.default);
}

Expand Down
6 changes: 3 additions & 3 deletions server.js → server/config/serverConfig.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import mongoose from 'mongoose';
import { config } from 'dotenv';
config();
import envConfig from './envConfig.js';
const db = envConfig.SERVER;
const server = mongoose;

export const connect = () => {
server
.connect(process.env.MONGO)
.connect(db)
.then(() => {
console.log('connected to mongoose');
})
Expand Down
2 changes: 1 addition & 1 deletion server/helpers/adminCheck.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import User from '../Users/userModel.js';
import User from '../application/users/userModel.js';
import { UnauthorizedError } from './errorHandler.js';

async function adminCheck(req, res, next) {
Expand Down
Loading