db-json-cli 1.0.0 → 1.0.2

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/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 hitorigotoh
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -0,0 +1,134 @@
1
+ # db-json-cli
2
+
3
+ JSON file 기반의 백엔드 서버 + JWT 인증 + CLI 도구
4
+
5
+ ---
6
+
7
+ ## 📦 설치
8
+
9
+ ```bash
10
+ npm install -g db-json-cli
11
+ ```
12
+
13
+ ---
14
+
15
+ ## 🚀 사용법
16
+
17
+ ### 1. 서버 시작
18
+
19
+ ```bash
20
+ db-json-cli --db ./path/to/db.json --port 4000
21
+ ```
22
+
23
+ - `--db` : JSON 파일 경로
24
+ - `--port` : 서버 포트 (기본 4000)
25
+
26
+ ---
27
+
28
+ ### 2. JSON 구조
29
+
30
+ ```json
31
+ {
32
+ "users": [],
33
+ "list": [{ "id": 1, "title": "Private item" }],
34
+ "public": [{ "id": 1, "title": "Public item" }],
35
+ "rules": {
36
+ "list": "private",
37
+ "public": "public"
38
+ }
39
+ }
40
+ ```
41
+
42
+ - `users` : 회원 정보 저장
43
+ - `list` : 인증 필요 데이터 ex)
44
+ - `public` : 누구나 접근 가능한 데이터 ex)
45
+ - `rules` : 각 키의 접근 권한 설정 (`private` 또는 `public`)
46
+
47
+ ---
48
+
49
+ ### 3. API
50
+
51
+ #### 회원가입
52
+
53
+ ```http
54
+ POST /register
55
+ Content-Type: application/json
56
+
57
+ {
58
+ "email": "example@example.com",
59
+ "password": "password123",
60
+ "name": "홍길동"
61
+ }
62
+ ```
63
+
64
+ 응답:
65
+
66
+ ```json
67
+ {
68
+ "accessToken": "...",
69
+ "refreshToken": "..."
70
+ }
71
+ ```
72
+
73
+ ---
74
+
75
+ #### 로그인
76
+
77
+ ```http
78
+ POST /login
79
+ Content-Type: application/json
80
+
81
+ {
82
+ "email": "example@example.com",
83
+ "password": "password123"
84
+ }
85
+ ```
86
+
87
+ 응답:
88
+
89
+ ```json
90
+ {
91
+ "accessToken": "...",
92
+ "refreshToken": "..."
93
+ }
94
+ ```
95
+
96
+ ---
97
+
98
+ #### 데이터 조회
99
+
100
+ - **인증 필요 데이터** (`private`)
101
+
102
+ ```http
103
+ GET /list/1
104
+ Authorization: Bearer <accessToken>
105
+ ```
106
+
107
+ - **인증 불필요 데이터** (`public`)
108
+
109
+ ```http
110
+ GET /public/1
111
+ ```
112
+
113
+ - 여러 아이템 조회 시 범위 지정 가능
114
+
115
+ ```http
116
+ GET /list?from=1&to=10
117
+ ```
118
+
119
+ ---
120
+
121
+ ### 4. CLI 옵션
122
+
123
+ ```bash
124
+ db-json-cli --db ./src/db/db.json --port 5000
125
+ ```
126
+
127
+ - `--db` : JSON 파일 경로
128
+ - `--port` : 포트
129
+
130
+ ---
131
+
132
+ ### 5. 라이선스
133
+
134
+ MIT © 2025 정지헌
package/package.json CHANGED
@@ -1,7 +1,24 @@
1
1
  {
2
2
  "name": "db-json-cli",
3
- "version": "1.0.0",
4
- "description": "JSON file based backend server with JWT auth and CLI",
3
+ "version": "1.0.2",
4
+ "license": "MIT",
5
+ "description": "Lightweight JSON-based backend server with JWT authentication and CLI support",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/your-username/db-json-cli.git"
9
+ },
10
+ "homepage": "https://github.com/your-username/db-json-cli#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/your-username/db-json-cli/issues"
13
+ },
14
+ "keywords": [
15
+ "json-server",
16
+ "cli",
17
+ "jwt",
18
+ "mock-server",
19
+ "express",
20
+ "api"
21
+ ],
5
22
  "bin": {
6
23
  "db-json-cli": "./bin/db-json-cli.js"
7
24
  },
package/src/auth.js CHANGED
@@ -4,22 +4,22 @@ import bcrypt from "bcryptjs";
4
4
  const ACCESS_SECRET = "access-secret";
5
5
  const REFRESH_SECRET = "refresh-secret";
6
6
 
7
- export async function hashPassword(password) {
7
+ export const hashPassword = async (password) => {
8
8
  const salt = await bcrypt.genSalt(10);
9
9
  return bcrypt.hash(password, salt);
10
- }
10
+ };
11
11
 
12
- export async function comparePassword(password, hash) {
12
+ export const comparePassword = async (password, hash) => {
13
13
  return bcrypt.compare(password, hash);
14
- }
14
+ };
15
15
 
16
- export function generateTokens(payload) {
16
+ export const generateTokens = async (payload) => {
17
17
  const accessToken = jwt.sign(payload, ACCESS_SECRET, { expiresIn: "1h" });
18
18
  const refreshToken = jwt.sign(payload, REFRESH_SECRET, { expiresIn: "7d" });
19
19
  return { accessToken, refreshToken };
20
- }
20
+ };
21
21
 
22
- export function authMiddleware(req, res, next) {
22
+ export const authMiddleware = async (req, res, next) => {
23
23
  const auth = req.headers["authorization"];
24
24
  if (!auth) return res.status(401).json({ message: "No token" });
25
25
 
@@ -31,115 +31,4 @@ export function authMiddleware(req, res, next) {
31
31
  } catch (e) {
32
32
  return res.status(401).json({ message: "Invalid token" });
33
33
  }
34
- }
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
34
+ };
package/src/server.js CHANGED
@@ -4,19 +4,18 @@ import bodyParser from "body-parser";
4
4
  import cors from "cors";
5
5
  import { hashPassword, comparePassword, generateTokens, authMiddleware } from "./auth.js";
6
6
 
7
- export async function startServer(dbPath, port = 4000) {
7
+ export const startServer = async (dbPath, port = 4000) => {
8
8
  const app = express();
9
9
  app.use(cors());
10
10
  app.use(bodyParser.json());
11
11
 
12
- // 초기 JSON 읽기
13
- let db = { users: [], list: [] };
12
+ // JSON Load
13
+ let db = { users: [], rules: {} };
14
14
  if (fs.existsSync(dbPath)) db = await fs.readJson(dbPath);
15
15
 
16
- // JSON 저장 함수
17
16
  const saveDB = async () => fs.writeJson(dbPath, db, { spaces: 2 });
18
17
 
19
- // ================== REGISTER ==================
18
+ // 🔹 REGISTER
20
19
  app.post("/register", async (req, res) => {
21
20
  const { email, password, name } = req.body;
22
21
  if (!email || !password) return res.status(400).json({ message: "Email/password required" });
@@ -34,7 +33,7 @@ export async function startServer(dbPath, port = 4000) {
34
33
  res.json(tokens);
35
34
  });
36
35
 
37
- // ================== LOGIN ==================
36
+ // 🔹 LOGIN
38
37
  app.post("/login", async (req, res) => {
39
38
  const { email, password } = req.body;
40
39
  const user = db.users.find((u) => u.email === email);
@@ -47,10 +46,53 @@ export async function startServer(dbPath, port = 4000) {
47
46
  res.json(tokens);
48
47
  });
49
48
 
50
- // ================== GET LIST (Protected) ==================
51
- app.get("/list", authMiddleware, (req, res) => {
52
- res.json(db.list);
49
+ // 🔹 AUTO ROUTES
50
+ Object.keys(db).forEach((key) => {
51
+ if (["users", "rules"].includes(key)) return;
52
+ const isPrivate = db.rules?.[key] === "private";
53
+
54
+ const route = express.Router();
55
+
56
+ // ✅ GET /key
57
+ route.get("/", async (req, res) => {
58
+ const { from, to } = req.query;
59
+ let data = db[key];
60
+
61
+ if (from && to) {
62
+ const fromNum = Number(from);
63
+ const toNum = Number(to);
64
+ data = data.filter((item) => item.id >= fromNum && item.id <= toNum);
65
+ }
66
+
67
+ res.json(data);
68
+ });
69
+
70
+ // ✅ GET /key/:id
71
+ route.get("/:id", async (req, res) => {
72
+ const id = Number(req.params.id);
73
+ const item = db[key].find((i) => i.id === id);
74
+ if (!item) return res.status(404).json({ message: "Not found" });
75
+ res.json(item);
76
+ });
77
+
78
+ // ✅ POST /key
79
+ route.post("/", async (req, res) => {
80
+ const newItem = req.body;
81
+ if (!newItem || typeof newItem !== "object") return res.status(400).json({ message: "Invalid body" });
82
+
83
+ const id = db[key].length ? Math.max(...db[key].map((i) => i.id)) + 1 : 1;
84
+ const item = { id, ...newItem };
85
+ db[key].push(item);
86
+ await saveDB();
87
+ res.json(item);
88
+ });
89
+
90
+ if (isPrivate) {
91
+ app.use(`/${key}`, authMiddleware, route);
92
+ } else {
93
+ app.use(`/${key}`, route);
94
+ }
53
95
  });
54
96
 
55
- app.listen(port, () => console.log(`db-json-cli server running on port ${port}`));
56
- }
97
+ app.listen(port, () => console.log(`✅ db-json-cli running on http://localhost:${port}`));
98
+ };