Step-by-step guide to add new mock APIs to the Tarekat Mock Server
Before adding a new API, define its purpose and structure:
Create a JSON file in the mocks/ directory with your mock responses:
// mocks/your-service.json
{
"success": {
"code": "S00200",
"message": "Success",
"data": {
"id": "12345",
"name": "Sample Item",
"status": "active",
"createdAt": "2024-01-01T00:00:00Z"
}
},
"list": [
{
"id": "1",
"name": "Item 1",
"status": "active"
},
{
"id": "2",
"name": "Item 2",
"status": "inactive"
}
]
}
// mocks/complex-service.json
{
"responses": {
"create": {
"success": {
"code": "S00200",
"message": "Created successfully",
"data": {
"referenceNumber": "REF{{timestamp}}",
"status": "pending",
"details": {
"submittedBy": "user123",
"submissionDate": "{{currentDate}}",
"estimatedCompletion": "{{futureDate}}"
}
}
}
},
"update": {
"success": {
"code": "S00200",
"message": "Updated successfully",
"data": {
"referenceNumber": "{{refNumber}}",
"status": "updated",
"lastModified": "{{currentDate}}"
}
}
}
}
}
// Error scenarios in your mock data
{
"errors": {
"validation": {
"code": "E00400",
"message": "Validation failed",
"details": {
"field": "{{invalidField}}",
"reason": "Required field missing"
}
},
"notFound": {
"code": "E00404",
"message": "Resource not found",
"details": {
"requestedId": "{{requestedId}}",
"suggestion": "Please check the ID and try again"
}
},
"serverError": {
"code": "E00500",
"message": "Internal server error",
"details": {
"timestamp": "{{currentDate}}",
"errorId": "ERR{{timestamp}}"
}
}
}
}
{{timestamp}}, {{currentDate}} for dynamic data in your middleware.
Create a middleware file in the middlewares/ directory to handle your API logic:
// middlewares/your-service.js
module.exports = function(mocks) {
return function(req, res, next) {
const path = req.path;
const method = req.method;
// Handle your specific endpoints
if (path.startsWith('/v1/your-service/')) {
// GET /v1/your-service/list
if (path === '/v1/your-service/list' && method === 'GET') {
return res.json(mocks.yourService.list);
}
// POST /v1/your-service/create
if (path === '/v1/your-service/create' && method === 'POST') {
const response = { ...mocks.yourService.success };
// Add dynamic data
response.data.id = generateId();
response.data.createdAt = new Date().toISOString();
return res.json(response);
}
// GET /v1/your-service/:id
const idMatch = path.match(/^\/v1\/your-service\/(\d+)$/);
if (idMatch && method === 'GET') {
const id = idMatch[1];
const response = { ...mocks.yourService.success };
response.data.id = id;
return res.json(response);
}
// Handle errors
if (path === '/v1/your-service/error-test') {
return res.status(400).json(mocks.yourService.errors.validation);
}
}
// Continue to next middleware
next();
};
};
// Helper functions
function generateId() {
return Math.floor(Math.random() * 1000000).toString();
}
function getCurrentDate() {
return new Date().toISOString();
}
next() if your middleware doesn't handle the request.
Add your middleware to the main server configuration:
// server.js - Add these lines
// Import your middleware
const yourServiceMiddleware = require('./middlewares/your-service');
// Load your mock data
const yourServiceMocks = require('./mocks/your-service.json');
// Add mocks to the main mocks object
const mocks = {
// ... existing mocks
yourService: yourServiceMocks
};
// Register middleware (ORDER MATTERS!)
server.use(yourServiceMiddleware(mocks));
// Make sure this comes BEFORE the json-server router
server.use('/api', router);
server.use('/api', router) line to ensure it gets processed first.
Test your new API endpoints to ensure they work correctly:
# Test GET endpoint
curl -X GET http://localhost:3000/v1/your-service/list
# Test POST endpoint
curl -X POST http://localhost:3000/v1/your-service/create \
-H "Content-Type: application/json" \
-d '{"name": "Test Item", "description": "Test description"}'
# Test GET with ID
curl -X GET http://localhost:3000/v1/your-service/123
# Test error scenario
curl -X GET http://localhost:3000/v1/your-service/error-test
#!/bin/bash
# test-your-service.sh
echo "Testing Your Service API..."
BASE_URL="http://localhost:3000"
echo "1. Testing list endpoint..."
curl -s "$BASE_URL/v1/your-service/list" | jq '.'
echo -e "\n2. Testing create endpoint..."
curl -s -X POST "$BASE_URL/v1/your-service/create" \
-H "Content-Type: application/json" \
-d '{"name": "Test Item"}' | jq '.'
echo -e "\n3. Testing get by ID..."
curl -s "$BASE_URL/v1/your-service/123" | jq '.'
echo -e "\n4. Testing error scenario..."
curl -s "$BASE_URL/v1/your-service/error-test" | jq '.'
echo -e "\nTesting complete!"
// Postman Collection JSON
{
"info": {
"name": "Your Service API Tests",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Get List",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{baseUrl}}/v1/your-service/list",
"host": ["{{baseUrl}}"],
"path": ["v1", "your-service", "list"]
}
}
},
{
"name": "Create Item",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"name\": \"Test Item\",\n \"description\": \"Test description\"\n}"
},
"url": {
"raw": "{{baseUrl}}/v1/your-service/create",
"host": ["{{baseUrl}}"],
"path": ["v1", "your-service", "create"]
}
}
}
],
"variable": [
{
"key": "baseUrl",
"value": "http://localhost:3000"
}
]
}
Restart the server to load your new API:
# Stop the current server
docker-compose down
# Rebuild and start with your changes
docker-compose up --build -d
# Check server logs
docker-compose logs -f
# Test that server is running
curl http://localhost:3000/health
http://localhost:3000/v1/your-service/*
./mocks/your-service.json./middlewares/your-service.js./server.jscurl http://localhost:3000/v1/your-service/endpointdocker-compose down && docker-compose up --build -ddocker-compose logs -fcurl http://localhost:3000/healthStudy existing implementations for reference:
You've successfully learned how to add new APIs to the Tarekat Mock Server. Your new endpoints are now ready for frontend development and testing!