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

Semana 8: Crear y listar productos #6

Open
wants to merge 6 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
5 changes: 5 additions & 0 deletions express/mau1-5427/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PORT=3001
MONGO_USER=
MONGO_PASSWORD=
MONGO_HOSTNAME=
DB_NAME=
23 changes: 23 additions & 0 deletions express/mau1-5427/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Semana 8: Crear y Listar productos con Mongoose

Base de datos creada en MongoDB: `warehouse -> products`

Crear producto, ejemplo:

```bash
curl --request POST \
http://localhost:3001/products \
--header "Content-Type: application/json" \
--data '{
"name": "Olive Oil Dispenser Bottle",
"description": "Leaflai oil bottle is made of lead-free glass and is 100% healthy and environmentally friendly.",
"tags": ["kitchen", "picnic", "home"],
"value": 15.99
}'
```

Listar productos:

```bash
http://localhost:3001/products
```
32 changes: 32 additions & 0 deletions express/mau1-5427/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import mongoose from "mongoose";
// router
import { productRouter } from "./product/router.js";

// environment variables
const { PORT, MONGO_USER, MONGO_PASSWORD, MONGO_HOSTNAME, DB_NAME } = process.env;

const MONGO_URI = `mongodb+srv://${MONGO_USER}:${MONGO_PASSWORD}@${MONGO_HOSTNAME}/?retryWrites=true&w=majority`;

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
res.send("API Running");
});

// set up router
app.use("/products", productRouter);

app.listen(PORT,
() => {
console.log(`Server running at port ${PORT} 💻`);
console.log(`http://localhost:${PORT}`);

mongoose.connect(MONGO_URI, {
dbName: `${DB_NAME}`
})
}
)
19 changes: 19 additions & 0 deletions express/mau1-5427/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "mau1-5427",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev":"node --watch index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2",
"mongoose": "^7.3.1"
}
}
6 changes: 6 additions & 0 deletions express/mau1-5427/product/model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import mongoose from "mongoose";
import productSchema from "./schema.js";

const productModel = mongoose.model("product", productSchema);

export default productModel;
29 changes: 29 additions & 0 deletions express/mau1-5427/product/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import express from "express";
import productModel from "./model.js";
// crypto to generate the "product_id"
import crypto from "crypto";

export const productRouter = express.Router();

// List / READ all
productRouter.get("/", async (req, res) => {
const products = await productModel.find({}).limit(10);
Copy link

Choose a reason for hiding this comment

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

Unicamente sugiero se agregue el sort u ordenamiento por alguna columna de la lista de productos


res.status(200).json({
products
});
});

// CREATE
productRouter.post("/", async (req, res) => {
const product_id = crypto.randomBytes(16).toString("base64url");

const productToSave = { ...req.body, product_id };

const createdProduct = await productModel.create(productToSave);

res.status(201).json({
product: createdProduct
});
});

27 changes: 27 additions & 0 deletions express/mau1-5427/product/schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import mongoose from "mongoose";
import { Decimal128 } from "mongoose";

const productSchema = mongoose.Schema( {
product_id: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true,
},
description: {
type: String,
required: true
},
tags: {
type: [String]
},
value: {
type: Decimal128,
required: true
}
})

Copy link

Choose a reason for hiding this comment

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

Aunque es un ejercicio, siempre es bueno almacenar la fecha de alta del registro, ya que cuando menos lo esperes vas a ocupar saber en que fecha se dio de alta o se modifico el registro

Esto es a criterio.

export default productSchema;