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

Corrección búsqueda por criterio #164

Merged
merged 4 commits into from
Apr 14, 2022
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
3 changes: 2 additions & 1 deletion restapi/.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
DB_CONN_STRING="mongodb+srv://dede_es1a:[email protected]/myFirstDatabase?retryWrites=true&w=majority"
DB_NAME="dede-es1a"
DB_COLLECTION_NAME="myFirstDatabase"
DB_COLLECTION_NAME="myFirstDatabase"
DB_CONN_TEST_STRING="mongodb+srv://dede-es1a-Tests:[email protected]/myFirstDatabase?retryWrites=true&w=majority"
12 changes: 6 additions & 6 deletions restapi/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { Request, Response, Router } from 'express';
import {check} from 'express-validator';
import { addOrder, findOrdersByUserDni, getDeliveryCosts } from './controllers/OrderController';
import {findRocks, addRock, deleteRock, findRocksSedimentary, findRocksMetamorphic, findRocksFiery, findByCriteryText, findByCriteryNumber} from './controllers/RockController';
import { addOrder, findOrdersByUserEmail, getDeliveryCosts } from './controllers/OrderController';
import {findRocks, addRock, deleteRock, findRocksSedimentary, findRocksMetamorphic, findRocksFiery, findByCritery} from './controllers/RockController';
import {findUsers, addUser, deleteUser, loginUser, logout} from './controllers/UserController';
const User = require("./models/User");
const Rock = require("./models/Rock");
Expand All @@ -18,6 +18,8 @@ api.post("/users/login", loginUser);

api.get("/users/logout", logout);

api.post("/users/delete", deleteUser);


//Methods for product of the app
api.get("/rocks/list", findRocks);
Expand All @@ -28,16 +30,14 @@ api.get("/rocks/list/metamorphic", findRocksMetamorphic);

api.get("/rocks/list/fiery", findRocksFiery);

api.get("/rocks/list/criteryText", findByCriteryText);

api.get("/rocks/list/criteryNumber", findByCriteryNumber);
api.get("/rocks/list/critery", findByCritery);

api.post("/rocks/add", addRock);

api.post("/rocks/delete", deleteRock);

//Methods for product of the app
api.get("/orders/userList", findOrdersByUserDni);
api.get("/orders/userList", findOrdersByUserEmail);

api.post("/orders/add", addOrder);

Expand Down
14 changes: 8 additions & 6 deletions restapi/controllers/OrderController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,26 @@ const geocoder = NodeGeocoder(options);
const Order = require("../models/Order");


export const findOrdersByUserDni = async (req:Request, res:Response) => {
let dni = req.body.dni;
let query = {userDni : dni.toString()};
export const findOrdersByUserEmail = async (req:Request, res:Response) => {
let email = req.body.email;
let query = {userEmail : email.toString()};
const users = await Order.find(query)
res.send(users).json();
res.setHeader('Content-Type', 'application/json');
res.send(users);
};


export const addOrder = async (req:Request, res:Response): Promise<any> => {
const crypto = require('crypto');
const orderId = crypto.randomBytes(60);

let userDni = req.body.dni;
let email = req.body.email;
let price = req.body.price;
let productId = req.body.productId;

let order = new Order({
orderId: orderId,
dni: userDni,
userEmail: email,
price: price,
productId: productId
});
Expand Down
12 changes: 2 additions & 10 deletions restapi/controllers/RockController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,9 @@ export const findRocksMetamorphic = async (req:Request, res:Response) => {
res.send(rocks);
};

export const findByCriteryText = async (req:Request, res:Response) => {
export const findByCritery = async (req:Request, res:Response) => {
let critery = req.body.critery;
const rocks = await Rock.find({$or:[{name : critery}, {type : critery}, {texture : critery} ]})
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(rocks);
}

export const findByCriteryNumber = async (req:Request, res:Response) => {
let critery = req.body.critery;
const rocks = await Rock.find({$or:[{price : critery}, {mohsHardness : critery}, {density : critery}]})
const rocks = await Rock.find(critery)
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(rocks);
Expand Down
2 changes: 2 additions & 0 deletions restapi/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export const deleteUser = async (req: Request, res: Response): Promise<any> => {
let user = await User.deleteOne(
{ dni: dni }
);
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(user);
};

Expand Down
2 changes: 1 addition & 1 deletion restapi/models/Order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const mongooseOrders = require("mongoose")
const orderSchema = mongooseOrders.Schema({
orderId : String,
price : Number,
userDni : String,
userEmail : String,
productId : String
},{
versionKey: false
Expand Down
166 changes: 122 additions & 44 deletions restapi/tests/api.test.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,56 @@
import request, {Response} from 'supertest';
import request, { Response } from 'supertest';
import express, { Application } from 'express';
import * as http from 'http';
import bp from 'body-parser';
import cors from 'cors';
import api from '../api';
import {findUsers, addUser, deleteUser, loginUser, logout} from '../controllers/UserController';
import { findUsers, addUser, deleteUser, loginUser, logout } from '../controllers/UserController';
import path from 'path';

let app:Application;
let server:http.Server;
let app: Application;
let server: http.Server;
const mongoose = require('mongoose');
let envPath = path.resolve("../.env");
require('dotenv').config({ path: envPath });

let expressSession = require('express-session');
declare global {
namespace Express {
interface Request {
session: typeof expressSession;
}
}
}

beforeAll(async () => {

app = express();
const port: number = 5000;

const options: cors.CorsOptions = {
origin: ['http://localhost:3000']
};
app.use(cors(options));
app.use(bp.json());
app.use("/api", api)

api.get("/users/list", findUsers);
app.use(expressSession({
secret: 'abcdefg',
resave: true,
saveUninitialized: true,
}));

app.use("/api", api)

server = app.listen(port, ():void => {
console.log('Restapi server for testing listening on '+ port);
}).on("error",(error:Error)=>{
const port: number = 5000;
server = app.listen(port, (): void => {
console.log('Restapi server for testing listening on ' + port);
}).on("error", (error: Error) => {
console.error('Error occured: ' + error.message);
});

mongoose.connect("mongodb+srv://dede_es1a:[email protected]/myFirstDatabase?retryWrites=true&w=majority", {
mongoose.connect(process.env.DB_CONN_TEST_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true
});
});
});

afterAll(async () => {
Expand All @@ -41,51 +59,111 @@ afterAll(async () => {
})

describe('user ', () => {

jest.setTimeout(100000);
const crypto = require('crypto');
const pass = crypto.randomBytes(4).toString('utf8');

/**
* Test that we can list users without any error.
* Tests that a user can be created through the user without throwing any errors.
*/
it('can be listed',async () => {
const response:Response = await request(app).get("/users/list");
it('can be created correctly', async () => {

let username: string = 'Pablo'
let email: string = '[email protected]'
const response: Response = await request(app).post('/api/users/add')
.send({
dni: "1",
name: username,
email: email,
rol: 1,
password: pass,
repeatPassword: pass
})
.set('Accept', 'application/json')
expect(response.statusCode).toBe(200);
});

/**
* Tests that a user can be created through the productService without throwing any errors.
*/
it('can be created correctly', async () => {
let username:string = 'Pablo'
let email:string = '[email protected]'
const crypto = require('crypto');
const pass = crypto.randomBytes(4).toString('utf8');
const response:Response = await request(app).post('/users/add')
.send({dni: "1",
it('cant be created correctly', async () => {

let username: string = 'Pablo'
let email: string = '[email protected]'
const response: Response = await request(app).post('/api/users/add')
.send({
dni: "1",
name: username,
email: email,
rol: 1,
password: pass})
.set('Accept', 'application/json')
//expect(response.statusCode).toBe(200);
password: pass,
repeatPassword: pass
})
.set('Accept', 'application/json')
expect(response.statusCode).toBe(401);
});

/**
* Test that we can list users without any error.
*/
it('can be listed', async () => {
const response: Response = await request(app).get("/api/users/list");
expect(response.body[0].email).toBe("[email protected]");
expect(response.statusCode).toBe(200);
});

/**
* Test that we can login users without any error.
*/
it('can be login', async () => {
const response: Response = await request(app).post("/api/users/login")
.send({
email: "[email protected]",
password: pass
})
.set('Accept', 'application/json');
expect(response.statusCode).toBe(200);
});

/**
* Test that we can logout users without any error.
*/
it('can be logout', async () => {
const response: Response = await request(app).get("/api/users/logout");
expect(response.statusCode).toBe(200);
});

/**
* Tests that a user can be deleted through the user without throwing any errors.
*/
it('can be deleted', async () => {
const response: Response = await request(app).post("/api/users/delete")
.send({ dni: "1" })
.set('Accept', 'application/json');
expect(response.statusCode).toBe(200);
});

});

describe('product ', () => {
it('can be listed',async () => {
const response:Response = await request(app).get("/rocks/list");
// expect(response.statusCode).toBe(200);
jest.setTimeout(10000);
it('can be listed', async () => {
const response: Response = await request(app).get("/api/rocks/list");
expect(response.statusCode).toBe(200);
});

it('can be created correctly', async () => {
const response:Response = await request(app).post('/rocks/add').
send({rockId:"prueba",
name: "prueba",
type: "prueba",
description: "prueba",
price: 1,
mohsHardness:1,
density:1,
texture:"prueba",
img: "prueba"})
.set('Accept', 'application/json')
// expect(response.statusCode).toBe(200);
const response: Response = await request(app).post('/api/rocks/add').
send({
rockId: "prueba",
name: "prueba",
type: "prueba",
description: "prueba",
price: 1,
mohsHardness: 1,
density: 1,
texture: "prueba",
img: "prueba"
})
.set('Accept', 'application/json')
expect(response.statusCode).toBe(200);
});
});