360-mock-server 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zahidrahimoon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # šŸš€ Mock API Server
2
+
3
+ Zero-config dynamic mock REST API server. Perfect for frontend development when backend isn't ready.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # Global installation (recommended)
9
+ npm install -g 360-mock-server
10
+
11
+ # Or use npx directly
12
+ npx 360-mock-server start
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```bash
18
+ # Navigate to your project
19
+ cd my-frontend-project
20
+
21
+ # Initialize (creates mock-data.json)
22
+ 360-mock init
23
+
24
+ # Start server
25
+ 360-mock start
26
+ ```
27
+
28
+ Server runs at `http://localhost:3000`
29
+
30
+ ---
31
+
32
+ ## CLI Commands
33
+
34
+ | Command | Description |
35
+ |---------|-------------|
36
+ | `360-mock start` | Start the server |
37
+ | `360-mock init` | Create mock-data.json |
38
+ | `360-mock list` | Show available resources |
39
+ | `360-mock reset` | Clear all data |
40
+
41
+ ### Options
42
+
43
+ ```bash
44
+ 360-mock start --port 4000 # Custom port
45
+ 360-mock start --file db.json # Custom data file
46
+ 360-mock --help # Show help
47
+ 360-mock --version # Show version
48
+ ```
49
+
50
+ ---
51
+
52
+ ## API Usage
53
+
54
+ ### Any endpoint works automatically!
55
+
56
+ Just POST to any endpoint - it creates the resource:
57
+
58
+ ```bash
59
+ # These all work without configuration:
60
+ POST /users
61
+ POST /products
62
+ POST /orders
63
+ POST /anything-you-want
64
+ ```
65
+
66
+ ### Full CRUD Operations
67
+
68
+ | Method | Endpoint | Description |
69
+ |--------|----------|-------------|
70
+ | GET | `/users` | Get all users |
71
+ | GET | `/users/1` | Get user by ID |
72
+ | POST | `/users` | Create user |
73
+ | PUT | `/users/1` | Replace user |
74
+ | PATCH | `/users/1` | Update user |
75
+ | DELETE | `/users/1` | Delete user |
76
+ | DELETE | `/users` | Delete all users |
77
+
78
+ ### Query Parameters
79
+
80
+ ```bash
81
+ GET /users?name=john # Filter by name
82
+ GET /users?_sort=name # Sort by field
83
+ GET /users?_order=desc # Sort order
84
+ GET /users?_limit=10&_page=2 # Pagination
85
+ ```
86
+
87
+ ---
88
+
89
+ ## Frontend Examples
90
+
91
+ ### Fetch API
92
+
93
+ ```javascript
94
+ // Create
95
+ const user = await fetch('http://localhost:3000/users', {
96
+ method: 'POST',
97
+ headers: { 'Content-Type': 'application/json' },
98
+ body: JSON.stringify({ name: 'Ali', email: 'ali@test.com' })
99
+ }).then(r => r.json());
100
+
101
+ // Read all
102
+ const users = await fetch('http://localhost:3000/users').then(r => r.json());
103
+
104
+ // Read one
105
+ const user = await fetch('http://localhost:3000/users/1').then(r => r.json());
106
+
107
+ // Update
108
+ await fetch('http://localhost:3000/users/1', {
109
+ method: 'PATCH',
110
+ headers: { 'Content-Type': 'application/json' },
111
+ body: JSON.stringify({ name: 'Ali Updated' })
112
+ });
113
+
114
+ // Delete
115
+ await fetch('http://localhost:3000/users/1', { method: 'DELETE' });
116
+ ```
117
+
118
+ ### Axios
119
+
120
+ ```javascript
121
+ import axios from 'axios';
122
+ const api = axios.create({ baseURL: 'http://localhost:3000' });
123
+
124
+ // Create
125
+ const { data: user } = await api.post('/users', { name: 'Ali' });
126
+
127
+ // Read
128
+ const { data: users } = await api.get('/users');
129
+
130
+ // Update
131
+ await api.patch(`/users/${id}`, { name: 'Updated' });
132
+
133
+ // Delete
134
+ await api.delete(`/users/${id}`);
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Features
140
+
141
+ - āœ… **Zero config** - Works out of the box
142
+ - āœ… **Any endpoint** - Auto-creates resources
143
+ - āœ… **Full CRUD** - GET, POST, PUT, PATCH, DELETE
144
+ - āœ… **Filtering** - Query parameter support
145
+ - āœ… **Sorting** - `?_sort=field&_order=desc`
146
+ - āœ… **Pagination** - `?_limit=10&_page=1`
147
+ - āœ… **Auto IDs** - Generated automatically
148
+ - āœ… **Timestamps** - createdAt, updatedAt
149
+ - āœ… **CORS enabled** - Works with any frontend
150
+
151
+ ---
152
+
153
+ ## License
154
+
155
+ MIT Ā© [zahidrahimoon](https://github.com/zahidrahimoon)
package/bin/cli.js ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { program } = require("commander");
4
+ const path = require("path");
5
+ const fs = require("fs");
6
+
7
+ const packageJson = require("../package.json");
8
+
9
+ program
10
+ .name("360-mock")
11
+ .description("šŸš€ Dynamic Mock REST API Server - Zero Config")
12
+ .version(packageJson.version);
13
+
14
+ program
15
+ .command("start")
16
+ .description("Start the mock server")
17
+ .option("-p, --port <port>", "Port number", "3000")
18
+ .option("-f, --file <filename>", "Data file name", "mock-data.json")
19
+ .action((options) => {
20
+ process.env.PORT = options.port;
21
+ process.env.DATA_FILE = path.join(process.cwd(), options.file);
22
+ require("../lib/server");
23
+ });
24
+
25
+ program
26
+ .command("init")
27
+ .description("Initialize mock-data.json in current directory")
28
+ .option("-f, --file <filename>", "Data file name", "mock-data.json")
29
+ .action((options) => {
30
+ const filePath = path.join(process.cwd(), options.file);
31
+ if (fs.existsSync(filePath)) {
32
+ console.log(`āš ļø ${options.file} already exists!`);
33
+ return;
34
+ }
35
+ const initialData = {
36
+ _info: "Add your mock data here. Each key becomes an API endpoint.",
37
+ users: [],
38
+ products: []
39
+ };
40
+ fs.writeFileSync(filePath, JSON.stringify(initialData, null, 2));
41
+ console.log(`āœ… Created ${options.file}`);
42
+ console.log(`\nšŸ“ File location: ${filePath}`);
43
+ console.log(`\nšŸš€ Run '360-mock start' to start the server`);
44
+ });
45
+
46
+ program
47
+ .command("reset")
48
+ .description("Reset/clear all mock data")
49
+ .option("-f, --file <filename>", "Data file name", "mock-data.json")
50
+ .action((options) => {
51
+ const filePath = path.join(process.cwd(), options.file);
52
+ if (!fs.existsSync(filePath)) {
53
+ console.log(`āš ļø ${options.file} not found!`);
54
+ return;
55
+ }
56
+ fs.writeFileSync(filePath, JSON.stringify({}, null, 2));
57
+ console.log(`āœ… Reset ${options.file} - All data cleared!`);
58
+ });
59
+
60
+ program
61
+ .command("list")
62
+ .description("List all available resources")
63
+ .option("-f, --file <filename>", "Data file name", "mock-data.json")
64
+ .action((options) => {
65
+ const filePath = path.join(process.cwd(), options.file);
66
+ if (!fs.existsSync(filePath)) {
67
+ console.log(`āš ļø ${options.file} not found! Run '360-mock init' first.`);
68
+ return;
69
+ }
70
+ try {
71
+ const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
72
+ const resources = Object.keys(data).filter(k => !k.startsWith("_"));
73
+ console.log(`\nšŸ“¦ Available Resources in ${options.file}:\n`);
74
+ if (resources.length === 0) {
75
+ console.log(" No resources yet. POST to any endpoint to create one!");
76
+ } else {
77
+ resources.forEach(resource => {
78
+ const count = Array.isArray(data[resource]) ? data[resource].length : 0;
79
+ console.log(` /${resource} (${count} items)`);
80
+ });
81
+ }
82
+ console.log("");
83
+ } catch (err) {
84
+ console.log(`āŒ Error reading ${options.file}`);
85
+ }
86
+ });
87
+
88
+ program.parse();
package/lib/server.js ADDED
@@ -0,0 +1,254 @@
1
+ const express = require("express");
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const cors = require("cors");
5
+
6
+ const app = express();
7
+ const PORT = process.env.PORT || 3000;
8
+ const DATA_FILE = process.env.DATA_FILE || path.join(process.cwd(), "mock-data.json");
9
+
10
+ app.use(cors());
11
+ app.use(express.json());
12
+
13
+ const readData = () => {
14
+ try {
15
+ if (!fs.existsSync(DATA_FILE)) {
16
+ fs.writeFileSync(DATA_FILE, JSON.stringify({}, null, 2));
17
+ return {};
18
+ }
19
+ const raw = fs.readFileSync(DATA_FILE, "utf-8");
20
+ return raw ? JSON.parse(raw) : {};
21
+ } catch (err) {
22
+ return {};
23
+ }
24
+ };
25
+
26
+ const writeData = (data) => {
27
+ fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
28
+ };
29
+
30
+ const getSingularName = (resource) => {
31
+ if (resource.endsWith("ies")) {
32
+ return resource.slice(0, -3) + "y";
33
+ }
34
+ if (resource.endsWith("s")) {
35
+ return resource.slice(0, -1);
36
+ }
37
+ return resource;
38
+ };
39
+
40
+ app.use((req, res, next) => {
41
+ const timestamp = new Date().toLocaleTimeString();
42
+ console.log(`[${timestamp}] šŸ“„ ${req.method} ${req.url}`);
43
+ if (req.body && Object.keys(req.body).length > 0) {
44
+ console.log(` Body:`, JSON.stringify(req.body));
45
+ }
46
+ next();
47
+ });
48
+
49
+ app.get("/", (req, res) => {
50
+ const data = readData();
51
+ const resources = Object.keys(data).filter(k => !k.startsWith("_"));
52
+ res.json({
53
+ message: "šŸš€ Mock API Server Running",
54
+ dataFile: DATA_FILE,
55
+ availableResources: resources,
56
+ endpoints: {
57
+ "GET /:resource": "Get all items",
58
+ "GET /:resource/:id": "Get single item",
59
+ "POST /:resource": "Create new item",
60
+ "PUT /:resource/:id": "Replace item",
61
+ "PATCH /:resource/:id": "Update item",
62
+ "DELETE /:resource/:id": "Delete item"
63
+ }
64
+ });
65
+ });
66
+
67
+ app.get("/:resource", (req, res) => {
68
+ const { resource } = req.params;
69
+ const data = readData();
70
+ if (!data[resource]) {
71
+ data[resource] = [];
72
+ writeData(data);
73
+ }
74
+ let items = [...data[resource]];
75
+ const queryParams = req.query;
76
+ if (Object.keys(queryParams).length > 0) {
77
+ items = items.filter(item => {
78
+ return Object.entries(queryParams).every(([key, value]) => {
79
+ if (key === "_limit" || key === "_page" || key === "_sort" || key === "_order") {
80
+ return true;
81
+ }
82
+ return String(item[key]).toLowerCase().includes(String(value).toLowerCase());
83
+ });
84
+ });
85
+ }
86
+ if (queryParams._sort) {
87
+ const sortField = queryParams._sort;
88
+ const order = queryParams._order === "desc" ? -1 : 1;
89
+ items.sort((a, b) => {
90
+ if (a[sortField] < b[sortField]) return -1 * order;
91
+ if (a[sortField] > b[sortField]) return 1 * order;
92
+ return 0;
93
+ });
94
+ }
95
+ if (queryParams._limit) {
96
+ const limit = parseInt(queryParams._limit);
97
+ const page = parseInt(queryParams._page) || 1;
98
+ const start = (page - 1) * limit;
99
+ items = items.slice(start, start + limit);
100
+ }
101
+ console.log(` āœ… Returning ${items.length} ${resource}`);
102
+ res.json(items);
103
+ });
104
+
105
+ app.get("/:resource/:id", (req, res) => {
106
+ const { resource, id } = req.params;
107
+ const data = readData();
108
+ if (!data[resource]) {
109
+ data[resource] = [];
110
+ writeData(data);
111
+ }
112
+ const item = data[resource].find((item) => String(item.id) === String(id));
113
+ if (!item) {
114
+ return res.status(404).json({
115
+ error: `${getSingularName(resource)} not found`,
116
+ id: id
117
+ });
118
+ }
119
+ console.log(` āœ… Found ${getSingularName(resource)} #${id}`);
120
+ return res.json(item);
121
+ });
122
+
123
+ app.post("/:resource", (req, res) => {
124
+ const { resource } = req.params;
125
+ const data = readData();
126
+ if (!data[resource]) {
127
+ data[resource] = [];
128
+ console.log(` šŸ“ Created new resource: ${resource}`);
129
+ }
130
+ const newId = req.body.id || Date.now();
131
+ if (data[resource].some(item => String(item.id) === String(newId))) {
132
+ return res.status(409).json({
133
+ error: "Item with this ID already exists",
134
+ id: newId
135
+ });
136
+ }
137
+ const newItem = {
138
+ id: newId,
139
+ ...req.body,
140
+ createdAt: new Date().toISOString()
141
+ };
142
+ data[resource].push(newItem);
143
+ writeData(data);
144
+ console.log(` āœ… Created ${getSingularName(resource)} #${newItem.id}`);
145
+ res.status(201).json(newItem);
146
+ });
147
+
148
+ app.put("/:resource/:id", (req, res) => {
149
+ const { resource, id } = req.params;
150
+ const data = readData();
151
+ if (!data[resource]) {
152
+ return res.status(404).json({
153
+ error: `Resource '${resource}' not found`
154
+ });
155
+ }
156
+ const index = data[resource].findIndex((item) => String(item.id) === String(id));
157
+ if (index === -1) {
158
+ return res.status(404).json({
159
+ error: `${getSingularName(resource)} not found`,
160
+ id: id
161
+ });
162
+ }
163
+ data[resource][index] = {
164
+ id: data[resource][index].id,
165
+ ...req.body,
166
+ updatedAt: new Date().toISOString()
167
+ };
168
+ writeData(data);
169
+ console.log(` āœ… Replaced ${getSingularName(resource)} #${id}`);
170
+ res.json(data[resource][index]);
171
+ });
172
+
173
+ app.patch("/:resource/:id", (req, res) => {
174
+ const { resource, id } = req.params;
175
+ const data = readData();
176
+ if (!data[resource]) {
177
+ return res.status(404).json({
178
+ error: `Resource '${resource}' not found`
179
+ });
180
+ }
181
+ const index = data[resource].findIndex((item) => String(item.id) === String(id));
182
+ if (index === -1) {
183
+ return res.status(404).json({
184
+ error: `${getSingularName(resource)} not found`,
185
+ id: id
186
+ });
187
+ }
188
+ data[resource][index] = {
189
+ ...data[resource][index],
190
+ ...req.body,
191
+ updatedAt: new Date().toISOString()
192
+ };
193
+ writeData(data);
194
+ console.log(` āœ… Updated ${getSingularName(resource)} #${id}`);
195
+ res.json(data[resource][index]);
196
+ });
197
+
198
+ app.delete("/:resource/:id", (req, res) => {
199
+ const { resource, id } = req.params;
200
+ const data = readData();
201
+ if (!data[resource]) {
202
+ return res.status(404).json({
203
+ error: `Resource '${resource}' not found`
204
+ });
205
+ }
206
+ const index = data[resource].findIndex((item) => String(item.id) === String(id));
207
+ if (index === -1) {
208
+ return res.status(404).json({
209
+ error: `${getSingularName(resource)} not found`,
210
+ id: id
211
+ });
212
+ }
213
+ const deletedItem = data[resource].splice(index, 1)[0];
214
+ writeData(data);
215
+ console.log(` āœ… Deleted ${getSingularName(resource)} #${id}`);
216
+ res.json({
217
+ message: `${getSingularName(resource)} deleted`,
218
+ deleted: deletedItem
219
+ });
220
+ });
221
+
222
+ app.delete("/:resource", (req, res) => {
223
+ const { resource } = req.params;
224
+ const data = readData();
225
+ if (!data[resource]) {
226
+ return res.status(404).json({
227
+ error: `Resource '${resource}' not found`
228
+ });
229
+ }
230
+ const count = data[resource].length;
231
+ data[resource] = [];
232
+ writeData(data);
233
+ console.log(` āœ… Cleared all ${resource} (${count} items)`);
234
+ res.json({
235
+ message: `All ${resource} deleted`,
236
+ deletedCount: count
237
+ });
238
+ });
239
+
240
+ app.use((req, res) => {
241
+ res.status(404).json({ error: "Endpoint not found" });
242
+ });
243
+
244
+ app.use((err, req, res, next) => {
245
+ console.error("āŒ Error:", err.message);
246
+ res.status(500).json({ error: "Internal server error" });
247
+ });
248
+
249
+ app.listen(PORT, () => {
250
+ console.log(`\nšŸš€ Mock API Server running on port ${PORT}`);
251
+ console.log(`šŸ“ Data file: ${DATA_FILE}\n`);
252
+ });
253
+
254
+ module.exports = app;
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "360-mock-server",
3
+ "version": "1.0.0",
4
+ "description": "šŸš€ Zero-config dynamic mock REST API server for frontend developers",
5
+ "main": "lib/server.js",
6
+ "bin": {
7
+ "360-mock": "./bin/cli.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node lib/server.js",
11
+ "test": "echo \"No tests yet\""
12
+ },
13
+ "keywords": [
14
+ "mock",
15
+ "api",
16
+ "rest",
17
+ "server",
18
+ "json",
19
+ "fake",
20
+ "backend",
21
+ "frontend",
22
+ "development",
23
+ "testing",
24
+ "crud"
25
+ ],
26
+ "author": "zahidrahimoon",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/zahidrahimoon/mock-server.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/zahidrahimoon/mock-server/issues"
34
+ },
35
+ "homepage": "https://github.com/zahidrahimoon/mock-server#readme",
36
+ "files": [
37
+ "bin/",
38
+ "lib/",
39
+ "README.md"
40
+ ],
41
+ "engines": {
42
+ "node": ">=14.0.0"
43
+ },
44
+ "dependencies": {
45
+ "commander": "^11.1.0",
46
+ "cors": "^2.8.5",
47
+ "express": "^4.18.2"
48
+ }
49
+ }