İlk olarak npm init –y komutu ile package.json oluşturulur. Oluşan dosyada scripts altında test ve start konfigürasyonları yapılır. Bu sayede proje terminalden npm start komutu ile kısayoldan çalıştırabilir.
“start”: “node src/index.js” –scripts altına yazılır.
Sıradaki adımda Express kurulumu yapılır. npm install express terminalden çalıştırılarak kurulum tamamlanır. Daha sonra npm install uuid ile uuid kütüphanesi kurulur.
Artık geliştirmeye başlanabilir. İlk olarak src dizini altına index.js oluşturabiliriz. Daha sonra endpointe istek atabilmek için .http uzantılı dosya oluşturularak vs code içerisinde REST CLİENT eklentisi kurulur.
const express = require("express");
const { v4: uuidv4 } = require("uuid");
const app = express();
app.use(express.json());
const PORT = 3000;
const APIKEY = "denemekey";
/**
* Başarılı response
*/
function successResposne(message, data) {
return {
success: true,
error: null,
data,
meta: {
message,
version: "v1",
size: Array.isArray(data) ? data.length : data ? 1 : 0,
timestamp: new Date().toISOString()
}
};
}
/**
* Hatalı response
*/
function errorResposne(message) {
return {
success: false,
error: {
message
},
data: null,
meta: {
version: "v1",
size: 0,
timestamp: new Date().toISOString()
}
};
}
/**
* API KEY Middleware
*/
function middlewareConfing(req, res, next) {
const key = req.header("x-api-key");
if (!key) {
return res.status(401).json(errorResposne("Api key not null"));
}
if (key !== APIKEY) {
return res.status(403).json(errorResposne("Invalid Api Key"));
}
next();
}
app.use(middlewareConfing);
/**
* Root endpoint
*/
app.get("/", (req, res) => {
return res.status(200).json(
successResposne("App running on /api/v1/orders", null)
);
});
/**
* Mock Database
*/
const orders = [];
orders.push({
id: uuidv4(),
ordername: "Deneme Ürün",
customer: "Selahaddin",
timestamp: new Date().toISOString()
});
/**
* Body Validation Middleware
*/
function validateBody(req, res, next) {
const body = req.body;
if (!body) {
return res.status(400).json(
errorResposne("Request body must not be empty")
);
}
const { customer, ordername } = body;
if (!customer?.trim()) {
return res.status(400).json(
errorResposne("customer must not empty")
);
}
if (!ordername?.trim()) {
return res.status(400).json(
errorResposne("ordername must not empty")
);
}
next();
}
/**
* Id Validation Middleware
*/
function validateId(req, res, next) {
const id = req.params.id;
if (!id?.trim()) {
return res.status(400).json(
errorResposne("invalid id")
);
}
next();
}
/**
* Order Control Middleware
*/
function checkOrder(req, res, next) {
const id = req.params.id;
const orderIndex = orders.findIndex(order => order.id === id);
if (orderIndex === -1) {
return res.status(404).json(
errorResposne("order not found")
);
}
req.orderIndex = orderIndex;
next();
}
/**
* GET ALL ORDERS
*/
app.get("/api/v1/orders", (req, res) => {
return res.status(200).json(
successResposne("All orders listed", orders)
);
});
/**
* GET ORDER BY ID
*/
app.get("/api/v1/orders/:id",
validateId,
checkOrder,
(req, res) => {
return res.status(200).json(
successResposne(
"Order listed",
orders[req.orderIndex]
)
);
});
/**
* CREATE ORDER
*/
app.post("/api/v1/orders",
validateBody,
(req, res) => {
const { ordername, customer } = req.body;
const order = {
id: uuidv4(),
ordername,
customer,
timestamp: new Date().toISOString()
};
orders.push(order);
return res.status(201).json(
successResposne("Order created", order)
);
});
/**
* UPDATE ORDER
*/
app.put("/api/v1/orders/:id",
validateId,
validateBody,
checkOrder,
(req, res) => {
const { ordername, customer } = req.body;
const order = {
id: req.params.id,
ordername,
customer,
timestamp: new Date().toISOString()
};
orders[req.orderIndex] = order;
return res.status(200).json(
successResposne("Order updated", order));
});
/**
* DELETE ORDER
*/
app.delete("/api/v1/orders/:id",validateId,checkOrder,(req, res) => {
orders.splice(req.orderIndex, 1);
return res.status(200).json(
successResposne("Order deleted", null)
);
});
/**
* Server
*/
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
.http uzantılı test requestlerini barındıran dosya
### ROOT (API çalışıyor mu?)
GET http://localhost:3000/
x-api-key: denemekey
### GET ALL orderS
GET http://localhost:3000/api/v1/orders
x-api-key: denemekey
### GET order BY ID (başarılı)
GET http://localhost:3000/api/v1/orders/1
x-api-key: denemekey
### GET order BY ID (geçersiz id)
GET http://localhost:3000/api/v1/orders/abc
x-api-key: denemekey
### CREATE order
POST http://localhost:3000/api/v1/orders
Content-Type: application/json
x-api-key: denemekey
{
"orderName": "orderfield",
"customer": "testcustomer"
}
### UPDATE order
PUT http://localhost:3000/api/v1/orders/1
Content-Type: application/json
x-api-key: denemekey
{
"orderName": "OrderNameupdate",
"customer": "José Mauro"
}
### UPDATE order (bulunamaz)
PUT http://localhost:3000/api/v1/orders/999
Content-Type: application/json
x-api-key: denemekey
{
"orderName": "Test",
"customer": "Test"
}
### UPDATE order (bulunamaz)
DELETE http://localhost:3000/api/v1/orders/3
Content-Type: application/json
x-api-key: denemekey
### DELETE order (bulunamaz)
DELETE http://localhost:3000/api/v1/orders/999
x-api-key: denemekey
### API KEY YOK (401)
GET http://localhost:3000/api/v1/orders
### API KEY HATALI (401)
GET http://localhost:3000/api/v1/orders
x-api-key: yanlışkey
### CREATE order (Eksik Alan - 400)
POST http://localhost:3000/api/v1/orders
Content-Type: application/json
x-api-key: denemekey
{
"orderName": "Eksik Alan"
}

Comments are closed.