Create-post-päätepisteen Rakentaminen
Tarkastellaan uuden julkaisun luomista käyttämällä "CREATE POST" -reittiä tiedostossa postsRoutes.js. Tämä reitti vastaa julkaisun luomisesta ja sen tallentamisesta tietolähteeseen (database/posts.json).
Reitin määrittely
Alla oleva koodi määrittelee "CREATE POST" -reitin käyttäen router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Tämä reitti on määritetty käsittelemään HTTP POST -pyyntöjä juuripolkuun
/; - Se käyttää
validatePostData-välimuistia, joka varmistaa, että pyynnön rungossa lähetetyt tiedot ovat kelvollisia ennen jatkamista.
Datan validointivälimuisti
Ennen kuin siirrytään reitin logiikkaan, tulee luoda datan validointivälimuisti. Tämä välimuisti varmistaa, että pyynnön rungossa lähetetty data on kelvollista ennen uuden julkaisun luomista.
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
validatePostData-funktio poimiiusername,postTitlejapostContentpyynnön rungosta;- Se tarkistaa, ovatko nämä kentät olemassa. Jos jokin niistä puuttuu (
!username,!postTitletai!postContent), palautetaan 400 (Bad Request) -statuskoodi ja virheilmoitus puuttuvista pakollisista kentistä; - Jos data on kelvollista, välimuisti kutsuu
next(), jolloin pyyntö jatkuu reittikäsittelijään (tässä tapauksessa "CREATE POST" -reitti).
Kun datan validointivälimuisti on käytössä, voidaan jatkaa "CREATE POST" -reitin logiikkaan.
Uuden postauksen tiedot
Uuden postauksen luomiseksi generoidaan yksilöllinen tunniste käyttämällä Date.now().toString(). Lisäksi poimitaan username, postTitle ja postContent pyynnön rungosta.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Uuden postauksen lisääminen tietokantaan
Seuraavat vaiheet kuvaavat, miten uusi postaus lisätään tietokantaan:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Olemassa oleva data luetaan JSON-tiedostosta asynkronisen
readData-funktion avulla, kuten aiemmin selitettiin; - Uusi postaus lisätään
data-taulukkoon; - Päivitetty
data-taulukko kirjoitetaan takaisin JSON-tiedostoon, jolloin uusi postaus tallentuu.
Vastauksen lähettäminen
Kun uusi julkaisu on luotu onnistuneesti, asiakkaalle lähetetään onnistumisilmoitus. Vastauksessa on tilakoodi 201 (Created) ja juuri luodun julkaisun tiedot JSON-muodossa.
res.status(201).json(newPost);
Virheenkäsittely
Reittikoodi kääritään try-catch-lohkoon mahdollisten virheiden käsittelemiseksi tietojen haun tai pyynnön käsittelyn aikana. Kaikki esiintyvät virheet kirjataan konsoliin vianmääritystä varten:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");
const router = express.Router();
// Function to read data from the JSON file
async function readData() {
try {
// Read the contents of the `posts.json` file
const data = await fs.readFile("./database/posts.json");
// Parse the JSON data into a JavaScript object
return JSON.parse(data);
} catch (error) {
// If an error occurs during reading or parsing, throw the error
throw error;
}
}
// GET ALL POSTS
router.get("/", async (req, res, next) => {
try {
// Call the `readData` function to retrieve the list of posts
const data = await readData();
// Send the retrieved data as the response
res.status(200).send(data);
} catch (error) {
// If an error occurs during data retrieval or sending the response
console.error(error.message); // Log the error to the console for debugging
}
});
// GET POST BY ID
router.get("/post/:id", async (req, res, next) => {
try {
// Extract the post ID from the request parameters
const postId = req.params.id;
// Read data from the JSON file
const data = await readData();
// Find the post with the matching ID
const post = data.find((post) => post.id === postId);
// If the post is not found, send a 404 response
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
// If the post is found, send it as the response
res.status(200).send(post);
}
} catch (error) {
// Handle errors by logging them and sending an error response
console.error(error.message);
}
});
// CREATE POST
router.post("/", validatePostData, async (req, res, next) => {
try {
// Generate a unique ID for the new post
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Add the new post to the data
data.push(newPost);
// Write the updated data back to the JSON file
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the new post
res.status(201).json(newPost);
} catch (error) {
// Handle errors by logging them to the console
console.error(error.message);
}
});
validateData.js-tiedoston täydellinen koodi
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
module.exports = validatePostData;
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Awesome!
Completion rate improved to 2.56
Create-post-päätepisteen Rakentaminen
Pyyhkäise näyttääksesi valikon
Tarkastellaan uuden julkaisun luomista käyttämällä "CREATE POST" -reittiä tiedostossa postsRoutes.js. Tämä reitti vastaa julkaisun luomisesta ja sen tallentamisesta tietolähteeseen (database/posts.json).
Reitin määrittely
Alla oleva koodi määrittelee "CREATE POST" -reitin käyttäen router.post():
router.post("/", validatePostData, async (req, res, next) => { ... }
- Tämä reitti on määritetty käsittelemään HTTP POST -pyyntöjä juuripolkuun
/; - Se käyttää
validatePostData-välimuistia, joka varmistaa, että pyynnön rungossa lähetetyt tiedot ovat kelvollisia ennen jatkamista.
Datan validointivälimuisti
Ennen kuin siirrytään reitin logiikkaan, tulee luoda datan validointivälimuisti. Tämä välimuisti varmistaa, että pyynnön rungossa lähetetty data on kelvollista ennen uuden julkaisun luomista.
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
validatePostData-funktio poimiiusername,postTitlejapostContentpyynnön rungosta;- Se tarkistaa, ovatko nämä kentät olemassa. Jos jokin niistä puuttuu (
!username,!postTitletai!postContent), palautetaan 400 (Bad Request) -statuskoodi ja virheilmoitus puuttuvista pakollisista kentistä; - Jos data on kelvollista, välimuisti kutsuu
next(), jolloin pyyntö jatkuu reittikäsittelijään (tässä tapauksessa "CREATE POST" -reitti).
Kun datan validointivälimuisti on käytössä, voidaan jatkaa "CREATE POST" -reitin logiikkaan.
Uuden postauksen tiedot
Uuden postauksen luomiseksi generoidaan yksilöllinen tunniste käyttämällä Date.now().toString(). Lisäksi poimitaan username, postTitle ja postContent pyynnön rungosta.
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
Uuden postauksen lisääminen tietokantaan
Seuraavat vaiheet kuvaavat, miten uusi postaus lisätään tietokantaan:
const data = await readData();
data.push(newPost);
await fs.writeFile("./database/posts.json", JSON.stringify(data));
- Olemassa oleva data luetaan JSON-tiedostosta asynkronisen
readData-funktion avulla, kuten aiemmin selitettiin; - Uusi postaus lisätään
data-taulukkoon; - Päivitetty
data-taulukko kirjoitetaan takaisin JSON-tiedostoon, jolloin uusi postaus tallentuu.
Vastauksen lähettäminen
Kun uusi julkaisu on luotu onnistuneesti, asiakkaalle lähetetään onnistumisilmoitus. Vastauksessa on tilakoodi 201 (Created) ja juuri luodun julkaisun tiedot JSON-muodossa.
res.status(201).json(newPost);
Virheenkäsittely
Reittikoodi kääritään try-catch-lohkoon mahdollisten virheiden käsittelemiseksi tietojen haun tai pyynnön käsittelyn aikana. Kaikki esiintyvät virheet kirjataan konsoliin vianmääritystä varten:
try {
// ... (code for retrieving and processing data)
} catch (error) {
console.error(error.message);
}
Complete code of the postsRoutes.js file at this step
const express = require("express");
const fs = require("fs/promises");
const validatePostData = require("../middlewares/validateData");
const router = express.Router();
// Function to read data from the JSON file
async function readData() {
try {
// Read the contents of the `posts.json` file
const data = await fs.readFile("./database/posts.json");
// Parse the JSON data into a JavaScript object
return JSON.parse(data);
} catch (error) {
// If an error occurs during reading or parsing, throw the error
throw error;
}
}
// GET ALL POSTS
router.get("/", async (req, res, next) => {
try {
// Call the `readData` function to retrieve the list of posts
const data = await readData();
// Send the retrieved data as the response
res.status(200).send(data);
} catch (error) {
// If an error occurs during data retrieval or sending the response
console.error(error.message); // Log the error to the console for debugging
}
});
// GET POST BY ID
router.get("/post/:id", async (req, res, next) => {
try {
// Extract the post ID from the request parameters
const postId = req.params.id;
// Read data from the JSON file
const data = await readData();
// Find the post with the matching ID
const post = data.find((post) => post.id === postId);
// If the post is not found, send a 404 response
if (!post) {
res.status(404).json({ error: "Post not found" });
} else {
// If the post is found, send it as the response
res.status(200).send(post);
}
} catch (error) {
// Handle errors by logging them and sending an error response
console.error(error.message);
}
});
// CREATE POST
router.post("/", validatePostData, async (req, res, next) => {
try {
// Generate a unique ID for the new post
const newPost = {
id: Date.now().toString(),
username: req.body.username,
postTitle: req.body.postTitle,
postContent: req.body.postContent,
};
// Read the existing data
const data = await readData();
// Add the new post to the data
data.push(newPost);
// Write the updated data back to the JSON file
await fs.writeFile("./database/posts.json", JSON.stringify(data));
// Send a success response with the new post
res.status(201).json(newPost);
} catch (error) {
// Handle errors by logging them to the console
console.error(error.message);
}
});
validateData.js-tiedoston täydellinen koodi
// Middleware to validate post data
function validatePostData(req, res, next) {
const { username, postTitle, postContent } = req.body;
if (!username || !postTitle || !postContent) {
return res.status(400).json({ error: "Missing required fields" });
}
// If data is valid, proceed to the next route handler
next();
}
module.exports = validatePostData;
Kiitos palautteestasi!