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

Week8 #9

Open
wants to merge 2 commits into
base: main
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
42 changes: 41 additions & 1 deletion 04-store-api/starter/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,41 @@
console.log('04 Store API')
require('dotenv').config();
require('express-async-errors');

const express = require('express');
const app = express();

const connectDB = require('./db/connect');
const productsRouter = require('./routes/products');

const notFoundMiddleware = require('./middleware/not-found');
const errorMiddleware = require('./middleware/error-handler');

// middleware
app.use(express.json());

// routes

app.get('/', (req, res) => {
res.send('<h1>Store API</h1><a href="/api/v1/products">products route</a>');
});

app.use('/api/v1/products', productsRouter);

// products route

app.use(notFoundMiddleware);
app.use(errorMiddleware);

const port = process.env.PORT || 3001;

const start = async () => {
try {
// connectDB
await connectDB(process.env.MONGO_URI);
app.listen(port, () => console.log(`Server is listening port ${port}...`));
} catch (error) {
console.log(error);
}
};

start();
82 changes: 82 additions & 0 deletions 04-store-api/starter/controllers/products.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const Product = require('../models/product');



const getAllProductsStatic = async (req, res) => {
const products = await Product.find({ price: { $gt: 30 } })
.sort('price')
.select('name price');


res.status(200).json({ products, nbHits: products.length });
};
const getAllProducts = async (req, res) => {
const { featured, company, name, sort, fields, numericFilters } = req.query;
const queryObject = {};


if (featured) {
queryObject.featured = featured === 'true' ? true : false;
}
if (company) {
queryObject.company = company;
}
if (name) {
queryObject.name = { $regex: name, $options: 'i' };
}
if (numericFilters) {
const operatorMap = {
'>': '$gt',
'>=': '$gte',
'=': '$eq',
'<': '$lt',
'<=': '$lte',
};
const regEx = /\b(<|>|>=|=|<|<=)\b/g;
let filters = numericFilters.replace(
regEx,
(match) => `-${operatorMap[match]}-`
);
const options = ['price', 'rating'];
filters = filters.split(',').forEach((item) => {
const [field, operator, value] = item.split('-');
if (options.includes(field)) {
queryObject[field] = { [operator]: Number(value) };
}
});
}

let result = Product.find(queryObject);
// sort
if (sort) {
const sortList = sort.split(',').join(' ');
result = result.sort(sortList);
} else {
result = result.sort('createdAt');
}



if (fields) {
const fieldsList = fields.split(',').join(' ');
result = result.select(fieldsList);
}

const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
const skip = (page - 1) * limit;

result = result.skip(skip).limit(limit);
// 23
// 4 7 7 7 2

const products = await result;
res.status(200).json({ products, nbHits: products.length });
};



module.exports = {
getAllProducts,
getAllProductsStatic,
};
1 change: 1 addition & 0 deletions 04-store-api/starter/db/connect.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const mongoose = require('mongoose')


const connectDB = (url) => {
return mongoose.connect(url, {
useNewUrlParser: true,
Expand Down
34 changes: 34 additions & 0 deletions 04-store-api/starter/models/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const mongoose = require('mongoose')

const productSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'product name must be provided'],
},
price: {
type: Number,
required: [true, 'product price must be provided'],
},
featured: {
type: Boolean,
default: false,
},
rating: {
type: Number,
default: 4.5,
},
createdAt: {
type: Date,
default: Date.now(),
},
company: {
type: String,
enum: {
values: ['ikea', 'liddy', 'caressa', 'marcos'],
message: '{VALUE} is not supported',
},
// enum: ['ikea', 'liddy', 'caressa', 'marcos'],
},
})

module.exports = mongoose.model('Product', productSchema)
Loading