Ƙirƙirar API Gateway ta amfani da Node.js tare da Express ɗakin karatu da haɗawa Swagger don takaddun API ana iya yin haka kamar haka:
Mataki 1: Saita Project da Sanya Libraries
- Ƙirƙiri sabon kundin adireshi don aikinku.
- Buɗe Command Prompt ko Terminal kuma kewaya zuwa kundin aikin:
cd path_to_directory
. - Fara kunshin npm:
npm init -y
. - Shigar da ɗakunan karatu da ake buƙata:.
npm install express ocelot swagger-ui-express
Mataki 2: Sanya Express kuma Ocelot
Ƙirƙiri fayil mai suna app.js
a cikin kundin aikin kuma buɗe shi don daidaitawa Express:
const express = require('express');
const app = express();
const port = 3000;
// Define routes here
app.listen(port,() => {
console.log(`API Gateway is running at http://localhost:${port}`);
});
Ƙirƙiri fayil ɗin daidaitawa mai suna ocelot-config.json
don ayyana tsarin buƙatun ku:
{
"Routes": [
{
"DownstreamPathTemplate": "/service1/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/api/service1/{everything}",
"UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE" ]
}
// Add other routes here
]
}
Mataki na 3: Haɗa Swagger
A cikin app.js
fayil ɗin, ƙara lambar mai zuwa don haɗawa Swagger:
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json'); // Create a swagger.json file
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Ƙirƙiri fayil mai suna swagger.json
a cikin kundin aikin kuma ayyana bayanan takaddun API:
{
"swagger": "2.0",
"info": {
"title": "API Gateway",
"version": "1.0.0"
},
"paths": {
"/api/service1/{everything}": {
"get": {
"summary": "Get data from Service 1",
"responses": {
"200": {
"description": "Successful response"
}
}
}
}
// Add definitions for other APIs here
}
}
Mataki na 4: Gudanar da Aikin
Buɗe Command Prompt ko Terminal kuma kewaya zuwa kundin tsarin aiki.
Gudanar da aikin tare da umarnin: node app.js
.
Mataki 5: Shiga Swagger UI
Shiga Swagger UI a adireshin: http://localhost:3000/api-docs
.
Lura cewa wannan misali ne mai sauƙi na yadda ake tura API Gateway da haɗawa Swagger ta amfani da Node.js. A aikace, ya kamata ku yi la'akari da abubuwa kamar tsaro, juzu'i, daidaitawar al'ada, da sauran la'akari.