Utekelezaji wa API ya Node.js Gateway- Kusimamia API Gateways na Swagger

Kuunda API Gateway kwa kutumia Node.js na Express maktaba na kujumuisha Swagger kwa hati za API kunaweza kufanywa kama ifuatavyo:

Hatua ya 1: Sanidi Mradi na Sakinisha Maktaba

  1. Unda saraka mpya ya mradi wako.
  2. Fungua Command Prompt au Terminal na uende kwenye saraka ya mradi: cd path_to_directory.
  3. Anzisha kifurushi cha npm: npm init -y.
  4. Sakinisha maktaba zinazohitajika :. npm install express ocelot swagger-ui-express

Hatua ya 2: Sanidi Express na Ocelot

Unda faili iliyopewa jina app.js kwenye saraka ya mradi na uifungue ili kusanidi 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}`);  
});  

Unda faili ya usanidi iliyopewa jina ocelot-config.json ili kufafanua uelekezaji wa ombi lako:

{  
  "Routes": [  
    {  
      "DownstreamPathTemplate": "/service1/{everything}",  
      "DownstreamScheme": "http",  
      "DownstreamHostAndPorts": [  
        {  
          "Host": "localhost",  
          "Port": 5001  
        }  
      ],  
      "UpstreamPathTemplate": "/api/service1/{everything}",  
      "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE" ]  
    }  
    // Add other routes here  
  ]  
}  

Hatua ya 3: Unganisha Swagger

Katika app.js faili, ongeza nambari ifuatayo ili kujumuisha 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));  

Unda faili iliyopewa jina swagger.json kwenye saraka ya mradi na ueleze habari ya hati ya 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  
  }  
}  

Hatua ya 4: Endesha Mradi

Fungua Command Prompt au Terminal na uende kwenye saraka ya mradi.

Endesha mradi kwa amri: node app.js.

Hatua ya 5: Ufikiaji Swagger wa UI

Fikia Swagger UI kwenye anwani: http://localhost:3000/api-docs.

Tafadhali kumbuka kuwa huu ni mfano rahisi wa jinsi ya kupeleka API Gateway na kuunganisha Swagger kwa kutumia Node.js. Katika mazoezi, unapaswa kuzingatia vipengele kama vile usalama, matoleo, usanidi maalum, na mambo mengine ya kuzingatia.