用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill build-api-gateway命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Index of Build Systems Skills
Coordination patterns for distributed dataflow systems including barriers, epochs, and distributed snapshots
Windowing, sessionization, time-series aggregation, and late data handling for streaming systems
基于 SOC 职业分类
正在显示 SKILL.md
| name | build-api-gateway |
| description | Build production-ready API gateway with intelligent routing, authentication,... |
| shortcut | gate |
| category | api |
| difficulty | advanced |
| estimated_time | 3-5 hours |
| version | 2.0.0 |
Creates enterprise-grade API gateway infrastructure that serves as the single entry point for all microservices. Implements intelligent request routing, authentication, rate limiting, load balancing, and response transformation. Supports Kong, Express Gateway, AWS API Gateway, and custom implementations.
Use this command when:
Do NOT use this command for:
Before running this command, ensure:
The command examines your system architecture:
Creates comprehensive gateway setup:
Builds layered middleware architecture:
Sets up intelligent traffic distribution:
Integrates comprehensive observability:
The command generates complete gateway infrastructure:
api-gateway/
├── src/
│ ├── gateway/
│ │ ├── server.js
│ │ ├── routes/
│ │ │ ├── router.js
│ │ │ └── service-registry.js
│ │ ├── middleware/
│ │ │ ├── authentication.js
│ │ │ ├── rate-limiter.js
│ │ │ ├── transformer.js
│ │ │ └── circuit-breaker.js
│ │ └── plugins/
│ │ ├── logging.js
│ │ └── monitoring.js
│ ├── config/
│ │ ├── gateway.config.js
│ │ ├── services.json
│ │ └── rate-limits.json
│ └── utils/
│ ├── load-balancer.js
│ └── service-discovery.js
├── kong/
│ ├── kong.yml
│ └── plugins/
├── tests/
│ └── gateway.test.js
└── docs/
└── api-gateway-guide.md
Scenario: Microservices gateway with JWT auth and rate limiting
Generated Express Gateway Implementation:
// gateway/server.js
import express from 'express';
import httpProxy from 'http-proxy-middleware';
import jwt from 'jsonwebtoken';
import rateLimit from 'express-rate-limit';
import CircuitBreaker from 'opossum';
class APIGateway {
constructor(config) {
this.app = express();
this.services = config.services;
this.setupMiddleware();
this.setupRoutes();
this.setupErrorHandling();
}
setupMiddleware() {
// CORS configuration
this.app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGINS);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header(, );
(req. === ) {
res.();
}
();
});
..( {
startTime = .();
res.(, {
duration = .() - startTime;
.({
: req.,
: req.,
: res.,
duration,
: req.,
: req.()
});
});
();
});
globalLimiter = ({
: * ,
: ,
: ,
: ,
:
});
..(globalLimiter);
}
() {
.(.).( {
{ path, target, auth, : limits, circuitBreaker } = config;
middlewares = [];
(auth) {
middlewares.(.(auth));
}
(limits) {
middlewares.(({
: limits. || ,
: limits. || ,
: {
req.?. || req.;
}
}));
}
breaker = (
.(target),
{
: circuitBreaker?. || ,
: circuitBreaker?. || ,
: circuitBreaker?. ||
}
);
breaker.(, {
.();
});
..(path, ...middlewares, {
breaker.(req, res, next)
.( {
res.().({
: ,
: name
});
});
});
});
}
() {
(req, res, next) => {
token = req..?.()[];
(!token) {
res.().({ : });
}
{
decoded = jwt.(token, process..);
req. = decoded;
(authConfig.) {
hasPermission = authConfig..(
decoded.?.(scope)
);
(!hasPermission) {
res.().({ : });
}
}
();
} (error) {
res.().({ : });
}
};
}
() {
httpProxy.({
target,
: ,
: {
proxyReq.(, req. || uuid.());
proxyReq.(, req.);
(req.) {
proxyReq.(, req..);
proxyReq.(, .(req..));
}
},
: {
proxyRes.[] = ;
proxyRes.[] = .() - req.;
}
});
}
}
{
: {
: ,
: ,
: {
: ,
: [, ]
},
: {
: ,
:
},
: {
: ,
: ,
:
}
},
: {
: ,
: ,
: {
:
},
: {
: ,
:
}
}
}
Scenario: Enterprise Kong gateway with plugins
Generated Kong Configuration:
# kong.yml
_format_version: "2.1"
services:
- name: user-service
url: http://user-service:3001
routes:
- name: user-routes
paths:
- /api/users
strip_path: false
methods:
- GET
- POST
- PUT
- DELETE
plugins:
- name: jwt
config:
key_claim_name: kid
secret_is_base64: false
- name: rate-limiting
config:
minute: 100
hour: 10000
policy: local
- name: request-transformer
config:
add:
headers:
- X-Gateway:Kong
-
Scenario: Gateway that combines multiple service responses
Generated API Composition:
// gateway/api-composer.js
class APIComposer {
async composeUserProfile(userId, req) {
// Parallel requests to multiple services
const [user, orders, preferences, recommendations] = await Promise.allSettled([
this.fetchUser(userId, req.headers),
this.fetchUserOrders(userId, req.headers),
this.fetchUserPreferences(userId, req.headers),
this.fetchRecommendations(userId, req.headers)
]);
// Compose response with error handling
const profile = {
user: user.status === 'fulfilled' ? user.value : null,
orders: orders.status === 'fulfilled' ? orders.value : [],
preferences: preferences.status === 'fulfilled' ? preferences.value : {},
recommendations: recommendations.status === 'fulfilled' ? recommendations.value : []
};
// Add metadata
profile._meta = {
composed_at: new ().(),
: .(profile).( v === || v === ),
: {
: user.,
: orders.,
: preferences.,
: recommendations.
}
};
profile;
}
() {
controller = ();
timeoutId = ( controller.(), timeout);
{
response = (url, {
...options,
: controller.
});
(timeoutId);
response.();
} (error) {
(timeoutId);
error;
}
}
}
Symptoms: 503 errors, timeouts Cause: Backend service down or overloaded Solution:
// Implement circuit breaker and fallback
breaker.fallback(() => ({
data: [],
source: 'cache',
message: 'Using cached data due to service unavailability'
}));
Prevention: Health checks, circuit breakers, graceful degradation
Symptoms: High rate of 401/403 errors Cause: Token expiry, invalid credentials, or permission issues Solution: Implement token refresh mechanism and clear error messages
Symptoms: 429 Too Many Requests Cause: Client exceeding configured limits Solution: Implement backoff strategy and provide rate limit headers
--frameworkkong, express-gateway, custom, aws-api-gatewaycustom/gateway --framework kong--authjwt, oauth2, api-key, basic, nonejwt/gateway --auth oauth2--load-balancerround-robin, least-connections, weighted, ip-hashround-robin/gateway --load-balancer weighted✅ DO:
❌ DON'T:
💡 TIPS:
/api-rate-limiter - Dedicated rate limiting setup/api-monitoring-dashboard - Gateway monitoring/service-mesh-configurator - Internal service communication/load-balancer-configurator - Advanced load balancing⚠️ Security Considerations:
Solution: Check service response times, reduce middleware chain, enable caching
Solution: Monitor event listeners, implement proper cleanup, limit request body size
Solution: Review route precedence, check path matching patterns
Last updated: 2025-10-11 Quality score: 9.5/10 Tested with: Kong 2.8, Express Gateway 1.16, Node.js 18