vite-plugin-json-server 0.1.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) 2022 Willyams Yujra
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,73 @@
1
+ **vite-plugin-json-server**
2
+ ![vite-plugin-json-server](https://github.com/yracnet/vite-plugin-json-server)
3
+
4
+ ## Description
5
+
6
+ vite-plugin-json-server is a plugin for Vite.js that integrates the json-server library, providing a simple way to serve a mock RESTful API during development. It enables you to quickly set up a server and define JSON data as endpoints, allowing you to simulate backend functionality without the need for a real server.
7
+ This plugin is designed to seamlessly integrate with Vite.js, leveraging its fast and efficient development server. By combining the power of Vite.js and json-server, you can streamline your frontend development process and focus on building your application.
8
+
9
+ ## Motivation
10
+
11
+ During frontend development, it is often necessary to work with an API before the actual backend is ready or available. This can cause delays and hinder the development process. With vite-plugin-json-server, you can overcome this hurdle by creating a mock API server with minimal effort. It allows you to define your data, endpoints, and even custom routes, providing a flexible and efficient solution for frontend development.
12
+
13
+ ## How to Use
14
+
15
+ 1. Install the plugin using npm or yarn:
16
+
17
+ ```bash
18
+ npm install vite-plugin-json-server --save-dev
19
+ ```
20
+
21
+ or
22
+
23
+ ```bash
24
+ yarn add vite-plugin-json-server --dev
25
+ ```
26
+
27
+ 2. Import and use the plugin in your `vite.config.js` file:
28
+
29
+ ```javascript
30
+ import jsonServer from "vite-plugin-json-server";
31
+ export default {
32
+ plugins: [
33
+ jsonServer({
34
+ // Configuration options
35
+ }),
36
+ ],
37
+ };
38
+ ```
39
+
40
+ 3. Start your Vite development server:
41
+
42
+ ```bash
43
+ npm run dev
44
+ ```
45
+
46
+ 4. Your mock API server will be available at `http://localhost:5173` by default.
47
+
48
+ ## Configuration
49
+
50
+ The plugin supports the following configuration options:
51
+
52
+ - `apiPath`: The base path for publishing json-server services. Default value: '/api'.
53
+ - `profile`: The profile name as directory name where other files are referenced. It can be used to customize data profile as needed. The default value is an empty string. You can use 'db-dev' or 'db1' as profile names.
54
+ - `source`: The resource to load and pass as main parameters to json-server. It is used with `join(profile, source)` when compiling.
55
+ - `static`: The name of the profile that contains static files. It is derived from `join(profile, source)`.
56
+ - `unwatch`: An inverse flag for the `watch` option that monitors and reloads the server when changes are detected.
57
+ - `readOnly`: A flag for json-server to enable read-only mode.
58
+ - `bodyParser`: A flag for json-server to enable body parsing.
59
+ - `noCors`: A flag for json-server to disable CORS (Cross-Origin Resource Sharing).
60
+ - `noGzip`: A flag for json-server to disable Gzip compression.
61
+ - `delay`: The delay value for json-server to simulate network latency.
62
+ - `id`: The value for json-server's `id` option.
63
+ - `foreignKeySuffix`: The value for json-server's `foreignKeySuffix` option.
64
+ - `quiet`: The value for json-server's `quiet` option.
65
+ Please refer to the [json-server documentation](https://github.com/typicode/json-server) for more details on these configuration options.
66
+
67
+ **Note:** The following options are not yet supported by the plugin and will be implemented in a future version: `routes`, `snapshots`, and `middlewares`.
68
+
69
+ **Note:** The `host` and `port` options are excluded form the plugin.
70
+
71
+ ## License
72
+
73
+ This plugin is licensed under the [MIT License](https://opensource.org/licenses/MIT).
package/dist/index.cjs ADDED
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ default: () => src_default,
34
+ pluginJsonServer: () => pluginJsonServer
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_json_server = __toESM(require("json-server"), 1);
38
+ var import_path = require("path");
39
+ var import_is = __toESM(require("json-server/lib/cli/utils/is"), 1);
40
+ var import_load = __toESM(require("json-server/lib/cli/utils/load"), 1);
41
+ var import_connect_pause = __toESM(require("connect-pause"), 1);
42
+ var assertPluginOptions = (pluginOptions) => {
43
+ const {
44
+ apiPath = "/api",
45
+ profile = "",
46
+ source = "db.json",
47
+ static: staticDir = "public",
48
+ // routes = "routes.json",
49
+ // snapshots = "snapshots",
50
+ // middlewares = [],
51
+ unwatch = false,
52
+ readOnly = false,
53
+ bodyParser = true,
54
+ noCors = false,
55
+ noGzip = false,
56
+ delay = 10,
57
+ id = "_id",
58
+ foreignKeySuffix = "_id",
59
+ quiet = false
60
+ } = pluginOptions;
61
+ return {
62
+ apiPath,
63
+ profile,
64
+ source: import_is.default.URL(source) ? source : (0, import_path.join)(profile, source),
65
+ static: (0, import_path.join)(profile, staticDir),
66
+ // routes: join(profile, staticDir),
67
+ // snapshots: join(profile, snapshots),
68
+ // middlewares: join(profile, middlewares),
69
+ unwatch,
70
+ readOnly,
71
+ bodyParser,
72
+ noCors,
73
+ noGzip,
74
+ delay,
75
+ id,
76
+ foreignKeySuffix,
77
+ quiet
78
+ };
79
+ };
80
+ var pluginJsonServer = (userOptions = {}) => {
81
+ const opts = assertPluginOptions(userOptions);
82
+ const createServer = async (config) => {
83
+ const { root, logger } = config;
84
+ try {
85
+ const routeOpts = {
86
+ id: opts.id,
87
+ foreignKeySuffix: opts.foreignKeySuffix
88
+ };
89
+ const defaultsOpts = {
90
+ static: (0, import_path.join)(root, opts.static),
91
+ logger: !opts.quiet,
92
+ readOnly: opts.readOnly,
93
+ noCors: opts.noCors,
94
+ noGzip: opts.noGzip,
95
+ bodyParser: opts.bodyParser
96
+ };
97
+ logger.info(" Loading: " + opts.source);
98
+ const db = await (0, import_load.default)(opts.source);
99
+ const app = import_json_server.default.create();
100
+ const router = import_json_server.default.router(db, routeOpts);
101
+ const defaults = import_json_server.default.defaults(defaultsOpts);
102
+ app.use(defaults);
103
+ if (opts.delay) {
104
+ logger.info(" Delay: " + opts.delay);
105
+ app.use((0, import_connect_pause.default)(opts.delay));
106
+ }
107
+ app.use(router);
108
+ return app;
109
+ } catch (error) {
110
+ console.log("createServer Error:", error);
111
+ return void 0;
112
+ }
113
+ };
114
+ return {
115
+ name: "vite-plugin-json-server",
116
+ configureServer: async (devServer) => {
117
+ const { config, watcher } = devServer;
118
+ let app = await createServer(config);
119
+ if (!opts.unwatch) {
120
+ const files = [opts.source];
121
+ watcher.on("change", async (file) => {
122
+ const reload = files.find((it) => file.endsWith(it));
123
+ if (reload) {
124
+ console.error(`Change file '${file}'`);
125
+ app = await createServer(config);
126
+ }
127
+ });
128
+ }
129
+ devServer.middlewares.use(
130
+ opts.apiPath,
131
+ (req, res, next) => {
132
+ app && app(req, res, next);
133
+ }
134
+ );
135
+ }
136
+ };
137
+ };
138
+ var src_default = pluginJsonServer;
139
+ // Annotate the CommonJS export names for ESM import in node:
140
+ 0 && (module.exports = {
141
+ pluginJsonServer
142
+ });
@@ -0,0 +1,20 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ type PluginOptions = {
4
+ source: string;
5
+ apiPath: string;
6
+ profile: string;
7
+ static: string;
8
+ unwatch: boolean;
9
+ readOnly: boolean;
10
+ bodyParser: boolean;
11
+ noCors: boolean;
12
+ noGzip: boolean;
13
+ delay: number;
14
+ id: string;
15
+ foreignKeySuffix: string;
16
+ quiet: boolean;
17
+ };
18
+ declare const pluginJsonServer: (userOptions?: Partial<PluginOptions>) => Plugin;
19
+
20
+ export { pluginJsonServer as default, pluginJsonServer };
package/dist/index.js ADDED
@@ -0,0 +1,107 @@
1
+ // src/index.ts
2
+ import jsonServer from "json-server";
3
+ import { join } from "path";
4
+ import is from "json-server/lib/cli/utils/is";
5
+ import load from "json-server/lib/cli/utils/load";
6
+ import pause from "connect-pause";
7
+ var assertPluginOptions = (pluginOptions) => {
8
+ const {
9
+ apiPath = "/api",
10
+ profile = "",
11
+ source = "db.json",
12
+ static: staticDir = "public",
13
+ // routes = "routes.json",
14
+ // snapshots = "snapshots",
15
+ // middlewares = [],
16
+ unwatch = false,
17
+ readOnly = false,
18
+ bodyParser = true,
19
+ noCors = false,
20
+ noGzip = false,
21
+ delay = 10,
22
+ id = "_id",
23
+ foreignKeySuffix = "_id",
24
+ quiet = false
25
+ } = pluginOptions;
26
+ return {
27
+ apiPath,
28
+ profile,
29
+ source: is.URL(source) ? source : join(profile, source),
30
+ static: join(profile, staticDir),
31
+ // routes: join(profile, staticDir),
32
+ // snapshots: join(profile, snapshots),
33
+ // middlewares: join(profile, middlewares),
34
+ unwatch,
35
+ readOnly,
36
+ bodyParser,
37
+ noCors,
38
+ noGzip,
39
+ delay,
40
+ id,
41
+ foreignKeySuffix,
42
+ quiet
43
+ };
44
+ };
45
+ var pluginJsonServer = (userOptions = {}) => {
46
+ const opts = assertPluginOptions(userOptions);
47
+ const createServer = async (config) => {
48
+ const { root, logger } = config;
49
+ try {
50
+ const routeOpts = {
51
+ id: opts.id,
52
+ foreignKeySuffix: opts.foreignKeySuffix
53
+ };
54
+ const defaultsOpts = {
55
+ static: join(root, opts.static),
56
+ logger: !opts.quiet,
57
+ readOnly: opts.readOnly,
58
+ noCors: opts.noCors,
59
+ noGzip: opts.noGzip,
60
+ bodyParser: opts.bodyParser
61
+ };
62
+ logger.info(" Loading: " + opts.source);
63
+ const db = await load(opts.source);
64
+ const app = jsonServer.create();
65
+ const router = jsonServer.router(db, routeOpts);
66
+ const defaults = jsonServer.defaults(defaultsOpts);
67
+ app.use(defaults);
68
+ if (opts.delay) {
69
+ logger.info(" Delay: " + opts.delay);
70
+ app.use(pause(opts.delay));
71
+ }
72
+ app.use(router);
73
+ return app;
74
+ } catch (error) {
75
+ console.log("createServer Error:", error);
76
+ return void 0;
77
+ }
78
+ };
79
+ return {
80
+ name: "vite-plugin-json-server",
81
+ configureServer: async (devServer) => {
82
+ const { config, watcher } = devServer;
83
+ let app = await createServer(config);
84
+ if (!opts.unwatch) {
85
+ const files = [opts.source];
86
+ watcher.on("change", async (file) => {
87
+ const reload = files.find((it) => file.endsWith(it));
88
+ if (reload) {
89
+ console.error(`Change file '${file}'`);
90
+ app = await createServer(config);
91
+ }
92
+ });
93
+ }
94
+ devServer.middlewares.use(
95
+ opts.apiPath,
96
+ (req, res, next) => {
97
+ app && app(req, res, next);
98
+ }
99
+ );
100
+ }
101
+ };
102
+ };
103
+ var src_default = pluginJsonServer;
104
+ export {
105
+ src_default as default,
106
+ pluginJsonServer
107
+ };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "vite-plugin-json-server",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "A plugin that integrates json-server with Vite.js, providing a simple way to mock REST APIs during development.",
6
+ "keywords": [
7
+ "vite",
8
+ "json",
9
+ "json-server",
10
+ "server",
11
+ "mock",
12
+ "mockAPI"
13
+ ],
14
+ "files": [
15
+ "dist",
16
+ "LICENSE"
17
+ ],
18
+ "license": "MIT",
19
+ "author": "Willyams Yujra <yracnet@gmail.com>",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/yracnet/vite-plugin-json-server"
23
+ },
24
+ "main": "dist/index.js",
25
+ "module": "dist/index.cjs",
26
+ "types": "dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "require": "./dist/index.js",
30
+ "import": "./dist/index.cjs",
31
+ "types": "./dist/index.d.ts"
32
+ }
33
+ },
34
+ "homepage": "https://github.com/yracnet/vite-plugin-json-server",
35
+ "bugs": "https://github.com/yracnet/vite-plugin-json-server/issues",
36
+ "scripts": {
37
+ "build": "tsup"
38
+ },
39
+ "dependencies": {},
40
+ "peerDependencies": {
41
+ "vite": "^4.0.0",
42
+ "json-server": "^0.17.3"
43
+ },
44
+ "devDependencies": {
45
+ "@types/connect": "^3.4.35",
46
+ "@types/json-server": "^0.14.4",
47
+ "@types/node": "^18.11.15",
48
+ "json-server": "^0.17.3",
49
+ "tsup": "^6.5.0",
50
+ "typescript": "^4.9.3",
51
+ "vite": "^4.0.0"
52
+ }
53
+ }