fetch-service-keep-need-server v3.0.8
fetch-service-keep-need (SKN)
A powerful frontend API mocking tool that helps AI understand your frontend better!
fetch-service-keep-need
(SKN for short) is a simple yet powerful API mocking library that helps frontend developers quickly simulate API responses without waiting for backend development to complete. With a simple configuration file, you can define various API scenarios, status codes, and response data, making frontend development more efficient.
Features
- 🚀 Zero Code Intrusion - API usage identical to native
fetch
- 📝 Configuration Driven - Define all endpoints and responses via JSON config
- 🔄 Scenario Switching - Configure multiple response scenarios for each endpoint
- ⏱ Delay Simulation - Simulate real network delays
- 🔐 Request & Response Encryption - Built-in AES encryption to protect sensitive data
- 🔌 One-Click Toggle - Easily switch between mock data and real requests
- 🚧 Path Parameters - Support for dynamic path parameters like
/api/users/:id
- 🧠 Dynamic Responses - Generate responses dynamically based on request data
Installation
npm install fetch-service-keep-need --save-dev
Or using yarn:
yarn add fetch-service-keep-need --dev
Quick Start
Run the visual demo
npm run visual-demo
1. Create Configuration File
Create a ServiceKeepNeed.json
file in your project root:
{
"settings": {
"enabled": true,
"encryption": {
"enabled": false
},
"responseEncryption": {
"enabled": false
}
},
"endpoints": [
{
"path": "/api/users",
"method": "GET",
"ex": {
"default": {
"status": 200,
"body": [
{ "id": 1, "name": "John", "role": "admin" },
{ "id": 2, "name": "Jane", "role": "user" }
]
},
"empty": {
"status": 200,
"body": []
}
}
}
]
}
2. Use in Your Code
import SKN from "fetch-service-keep-need";
// Basic usage identical to native fetch
async function getUsers() {
const response = await SKN.fetch("/api/users");
const data = JSON.parse(response);
console.log(data);
}
// Specify response scenario
async function getEmptyUsers() {
const response = await SKN.fetch("/api/users", {
sknKey: "empty", // Use the "empty" scenario response
});
const data = JSON.parse(response);
console.log(data); // Will return an empty array
}
Configuration File Details
The ServiceKeepNeed.json
file is the core of SKN, defining all mock endpoints and settings.
Global Settings
{
"settings": {
"enabled": true, // Global mock switch, set to false to use native fetch
"encryption": {
"enabled": true // Global request encryption switch
},
"responseEncryption": {
"enabled": true // Global response encryption switch
}
}
}
Endpoint Configuration
Each endpoint includes:
path
- Request path, supports path parameters like/api/users/:id
method
- HTTP method (GET, POST, PUT, DELETE, etc.)ex
- Collection of mock response scenariosencryption
- (Optional) Override global encryption settingresponseEncryption
- (Optional) Override global response encryption setting
Each response scenario can define:
status
- HTTP status codeheaders
- Response headersbody
- Response body (static object)bodyFunction
- Dynamic response function (as string)delay
- Response delay (milliseconds)
{
"endpoints": [
{
"path": "/api/login",
"method": "POST",
"ex": {
"success": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
},
"delay": 1000
},
"invalid_payload": {
"status": 400,
"body": {
"error": "Missing required field: password"
}
}
},
"encryption": false // Disable encryption for this endpoint
}
]
}
Advanced Usage
Dynamic Responses
You can create dynamic responses based on request data:
{
"path": "/api/users/:id",
"method": "GET",
"ex": {
"dynamic": {
"status": 200,
"bodyFunction": "return { id: parseInt(request.params.id), name: `User ${request.params.id}`, email: `user${request.params.id}@example.com` };"
}
}
}
The request
object contains:
url
- Full request URLmethod
- HTTP methodheaders
- Request headersparams
- Path parametersbody
- Request body (if present)
Request Encryption
When encryption is enabled, SKN automatically encrypts the request body and adds a SKNtoken
header:
// With encryption enabled (settings.encryption.enabled = true)
const response = await SKN.fetch("/api/secure-endpoint", {
method: "POST",
body: JSON.stringify({ username: "admin", password: "123456" }),
});
Generated request headers will include:
Content-Type: application/json
SKNRequestToken: a1b2c3d4e5f6g7h8i9j0
The request body will be encrypted.
Response Encryption
SKN can also encrypt responses from the server:
{
"path": "/api/sensitive-data",
"method": "GET",
"ex": {
"default": {
"status": 200,
"body": { "secretData": "sensitive information" }
}
},
"responseEncryption": true
}
The SKN client will automatically decrypt encrypted responses.
Server-side Decryption & Encryption
On the server side, you can use SKN tools to decrypt requests and encrypt responses:
const SKNServer = require("fetch-service-keep-need/server");
// Express middleware
app.use(express.json());
app.use(SKNServer.middleware());
// Or manual decryption
app.post("/api/secure", (req, res) => {
const token = req.headers["SKNRequestToken"];
const encryptedData = req.body;
try {
const decryptedData = SKNServer.decrypt(encryptedData, token);
// Process decrypted data...
// Encrypt response
const encrypted = SKNServer.encryptResponse({ result: "success" });
res.set("SKNResponseToken", encrypted.token);
res.send(encrypted.data);
} catch (error) {
res.status(400).send("Decryption failed");
}
});
Dynamic Mock Toggle
You can dynamically toggle mocking:
// Modify settings in the config file
const fs = require("fs");
const path = require("path");
const configPath = path.resolve(process.cwd(), "ServiceKeepNeed.json");
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
// Disable mocking
config.settings.enabled = false;
// Save changes
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
Why Choose SKN?
Development Efficiency
- Parallel Development - Frontend and backend can develop simultaneously
- Quick Scenario Switching - Easily switch between development, testing, and demo scenarios
- Zero Waiting - No need to wait for real API network delays
Security
- Data Encryption - Built-in AES encryption protects sensitive data
- Local Mocking - Sensitive data can be completely mocked locally, no need to send
AI Friendly
SKN's clear, intuitive configuration file structure allows AI tools (like Claude, GPT-4) to better understand your API structure and data models, providing more accurate code suggestions and completions. This makes SKN an ideal partner for AI-assisted development!
Examples
Check out the complete example project in the example directory.
Visual Demo
The package includes a complete visual demo with a web interface that allows you to:
- Toggle between mock and real API requests
- Visualize the communication between client and server
- Test different API endpoints
- View request and response details
- Explore the configuration
To run the visual demo:
npm run visual-demo
Then open your browser to http://localhost:3000
License
MIT
Contributions, issues, and pull requests are welcome!