Pages

Mongoose !


📕Cours 

→ https://dupontmongodb.blogspot.com/


🛟Tout en 1 

→ Mongoose par l'exemple !


Installation Mongodb ⚒️

 mongodb →

installation mongodb

🥷Code

https://github.com/dupontdenis/testMongo.git


💸Code avec mongoose

https://github.com/dupontdenis/TESTMONGOOSE.git


Test

https://github.com/dupontdenis/TESTCORSMONGO.git 



Let's start 


Model : Simulate a DB

 Learn how to simulate a model

https://github.com/dupontdenis/simu-db-fake-books.git


📌En action : 

🚩 PUT/DELETE how-to

 💡 Les navigateurs ne supportent que GET et POST en natif dans les formulaires. Découvrez comment gérer DELETE et PUT. 

Méthode CRUD

Support natif HTML

Solution avec Express

Create (POST)

✅ Oui

<form method="POST">

Read (GET)

✅ Oui

<form method="GET">

Update (PUT)

❌ Non

method-override + POST

Delete (DELETE)

❌ Non

method-override + POST




Delete/update

  • In this repository we keep things explicit and simple by using POST endpoints for update and delete actions (for example /posts/:id/update and /posts/:id/delete). Those endpoints accept normal POST form submissions and return normal redirects or rendered pages.

  • HTML forms only submit GET or POST. method-override is a middleware used to turn a POST into a PUT/DELETE on the server (usually by reading a hidden _method field or a query parameter).

  • This project was converted to an API-first, client-rendered demo where the server returns JSON and the frontend (in public/index.html and public/js/app.js) uses fetch() to perform CRUD operations.




Avancé : une seule vue pour edit/create https://github.com/dupontdenis/CRUD.git

API : how to

  

🛟→lien


🛩️→ lien


📅 Date DS

 


 Le premier DS aura lieu le 01 décembre.

🍕PizzasAPI

 






🚀 https://mypizzasapi.onrender.com/

{
  "message": "Welcome to Pizza API! 🍕",
  "description": "A simple REST API for pizzas - inspired by ghibliapi.dev",
  "endpoints": {
    "pizzas": "/API/pizzas",
    "pizzaById": "/API/pizzas/:id",
    "pizzasWithPrices": "/API/pizzasWithPrices",
    "ingredientPrices": "/API/ingredientPrices",
    🪛"pizzaSearchByIngredient": "/API/pizzas/search?ingredient=🧀",
"pizzaSinglePrice": "/API/pizzasWithPrices/:id/price", "customPrice": { "method": "POST", "path": "/API/pizzasWithPrices/compute", "body": { "ingredients": [ "🍅", "🧀" ] } } } }

Exemples : 
🪛Ainsi pour tester l'API avec ingredient=🧀
https://mypizzasapi.onrender.com/API/pizzas/search?ingredient=🧀
🪛Ainsi pour tester l'API avec ingredient=🍅 et ingredient=🍄
https://mypizzasapi.onrender.com/API/pizzas/search?ingredient=🍄&ingredient=🍅

🥷Pour tester : https://dupontdenis.github.io/testMyPizzasAPI/

projet

 

Souriez : projet

Clonez  https://github.com/dupontdenis/takepicture.git

Lancez dans un terminal le serveur avec la commande : 

node app



Dans votre navigateur allez http://localhost:3000/



see also   https://github.com/dupontdenis/Smill.git

Projet

 


Travail perso

 

DS

  


Mon tirage

Résultats du Loto



🪛 Comment afficher mon gain ?

NPM :


💥 Cours

🪛 Mon premier projet nodejs : TD 1

TD 2

💥Les modules

 Les modules se répartissent en trois catégories :

1️⃣les modules de fichiers,

2️⃣les modules Node

3️⃣les modules

1️⃣ Modules fichiers

2️⃣Modules Node

2.1 Process

2.2 Event

2.3 fs

2.4 Path

2.5 HTTP

Cours

TD

👹TD 'express)

Have fun !

  Analysez ce code ! 


const arr2 = [1, 2, 3];
const arr1 = [4, 5, 6, 7, 8];

const [small, large] = arr1.length < arr2.length
    ? [arr1, arr2]
    : [arr2, arr1];
console.log(small == arr2); // [1, 2, 3] [4, 5, 6, 7, 8]

const mapToppings = new Map([
  ["queen", ["🐷", "🍄", "🍅", "🧀"]],
  ["cheese", ["🧀", "🍅"]],
  ["oriental", ["🍅", "🐑", "🍄", "🌶"]],
  ["royal", ["🍅", "🌵"]],
]);

const order1 = [
  { name: "queen", ingredients: mapToppings.get("queen") },
  { name: "cheese", ingredients: mapToppings.get("cheese") },
  { name: "oriental", ingredients: mapToppings.get("oriental") },
  { name: "royal", ingredients: mapToppings.get("royal") },
];

const order2 = [
  { name: "queen-promo", ingredients: mapToppings.get("queen") },
  { name: "royal-promo", ingredients: mapToppings.get("royal") },
];

function intersectionBy(a, b, keyFn) {
  const setB = new Set(b.map(keyFn));
  return a.filter((item) => setB.has(keyFn(item)));
}

const common = intersectionBy(order1,
                              order2,
                              (pizza) => pizza.ingredients);
console.log(common);
// [{ name: "queen", ingredients: [...] }, { name: "royal", ingredients: [...] }]

Exemple de code bloquant



🚀 https://github.com/dupontdenis/fakeWait.git


Asynchronisme !

Introduction


Cours

Callback, promesses et Async/Await

Slides


BD (callback)

asynchrone exemple

🆘(sqlite node)


TD



🚀Asynchrone dans votre navigateur (es6)

Objectif : comprendre ce code

 

  1. async function* getLines() {
  2.   const data = [
  3.     "# Commentaire ignoré",
  4.     "Ligne utile 1",
  5.     "Ligne utile 2",
  6.     "# Autre commentaire",
  7.     "STOP",
  8.     "Ligne après STOP",
  9.   ];

  10.   for (const line of data) {
  11.     await new Promise((resolve) => setTimeout(resolve, 100)); // simule un délai
  12.     yield line;
  13.   }
  14. }

  15. async function processUntilStop(lines) {
  16.   for await (const line of lines) {
  17.     if (line === "STOP") break;
  18.     if (line.startsWith("#")) continue;
  19.     console.log(`Traitement : ${line}`);
  20.   }
  21.   console.log("🔚 Fin du traitement.");
  22. }

  23. processUntilStop(getLines());

Devoir

  Création d'un jeu. 

Règle du jeu : 

Le joueur a trois chances pour trouver un nombre secret !


Imaginez que vous soyez chef de projet, vous rédigez en urgence un prototype pour les membres de votre équipe. Ce prototype permet à tous de fixer les idées (proto).

👷 Il faudra l'implémenter en JS.

lecture

Analysez ce code :  

 







class BD {
constructor(db) {
    this.db = db;
  }

  /**
   * Finds items based on a query given as a JS object
   *
   * @param {object} query The query to match against (i.e. {name: 'paris'})
   * @param {function} callback   The callback to fire when the query has
   * completed running
   **/
  find(query, callback) {
    callback(
      this.db.filter(function (city) {
        for (const [key, value] of Object.entries(query)) {
          if (city[key] !== value) {
            return false;
          }
        }
        return true;
      })
    );
  }
}

// cities
const db = new BD([
  { name: "Vincennes", population: 40000 },
  { name: "Paris", population: 2161000 },
  { name: "roubais", population: 45000 },
]);
//console.log(s.db);

db.find({ population: 45000 }, function (cities) {
  for (let city of cities) {
    city["population"] = 50000;
  }
});

db.find({ name: "Paris" }, function (cities) {
  for (let city of cities) {
    city["capital"] = true;
  }
});

console.log(db);

db.find({ name: "Paris" }, function (cities) {
  const updatedCities = cities.map((city) => ({ ...city, capital: true }));
  console.log(updatedCities); // Only updated copies, db remains unchanged
});