entity-server-client 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 +21 -0
- package/README.md +51 -0
- package/build.mjs +26 -0
- package/dist/hooks/useEntityServer.d.ts +12 -0
- package/dist/index.d.ts +272 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +7 -0
- package/dist/react.d.ts +1 -0
- package/dist/react.js +2 -0
- package/dist/react.js.map +7 -0
- package/docs/apis.md +505 -0
- package/docs/react.md +80 -0
- package/package.json +38 -0
- package/src/hooks/useEntityServer.ts +50 -0
- package/src/index.ts +597 -0
- package/src/react.ts +1 -0
- package/tsconfig.json +14 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
// @ts-ignore
|
|
2
|
+
import { xchacha20poly1305 } from "@noble/ciphers/chacha";
|
|
3
|
+
// @ts-ignore
|
|
4
|
+
import { sha256 } from "@noble/hashes/sha2";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 엔티티 목록 조회 파라미터입니다.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* client.list("post", {
|
|
11
|
+
* page: 1, limit: 10,
|
|
12
|
+
* orderBy: "created_time", orderDir: "DESC",
|
|
13
|
+
* fields: ["seq", "title", "created_time"],
|
|
14
|
+
* conditions: { status: "active" },
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
export interface EntityListParams {
|
|
19
|
+
/** 조회 페이지 번호. 기본값: `1` */
|
|
20
|
+
page?: number;
|
|
21
|
+
/** 페이지당 레코드 수. 기본값: `20` */
|
|
22
|
+
limit?: number;
|
|
23
|
+
/** 정렬 기준 필드명 */
|
|
24
|
+
orderBy?: string;
|
|
25
|
+
/** 정렬 방향. 기본값: `"ASC"` */
|
|
26
|
+
orderDir?: "ASC" | "DESC";
|
|
27
|
+
/**
|
|
28
|
+
* 반환할 필드 목록.
|
|
29
|
+
*
|
|
30
|
+
* - **미지정 (기본값)**: 엔티티의 인덱스 필드만 반환합니다.
|
|
31
|
+
* 복호화를 건너뛰기 때문에 **가장 빠릅니다**.
|
|
32
|
+
* - `["*"]`: 전체 필드 반환 (복호화 수행).
|
|
33
|
+
* - 필드명 목록: 해당 필드만 반환합니다.
|
|
34
|
+
* 엔티티 설정에 `index`로 선언된 필드만 지정 가능합니다.
|
|
35
|
+
* 존재하지 않는 필드명을 지정하면 서버 에러가 발생합니다.
|
|
36
|
+
* - `seq`, `created_time`, `updated_time`, `license_seq`는 필드에 관계없이 항상 포함됩니다.
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* // 기본값 (인덱스 필드만, 가장 빠름)
|
|
40
|
+
* client.list("account")
|
|
41
|
+
* // 전체 필드
|
|
42
|
+
* client.list("account", { fields: ["*"] })
|
|
43
|
+
* // seq, name, email만
|
|
44
|
+
* client.list("account", { fields: ["seq", "name", "email"] })
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
fields?: string[];
|
|
48
|
+
/** 필터 조건. POST body로 전달됩니다. (예: `{ status: "active" }`) */
|
|
49
|
+
conditions?: Record<string, unknown>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* `query()` 메서드에 전달하는 SQL 쿼리 요청입니다.
|
|
54
|
+
*
|
|
55
|
+
* - `sql`: SELECT 전용 SQL. 인덱스 테이블만 조회 가능하며 JOIN 지원.
|
|
56
|
+
* - `params`: SQL 바인딩 파라미터 (`?` 플레이스홀더 대응).
|
|
57
|
+
* - `limit`: 최대 반환 건수 (최대 1000. 미지정 시 서버 기본값 적용).
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* client.query("order", {
|
|
61
|
+
* sql: `SELECT o.seq, o.status, u.name
|
|
62
|
+
* FROM order o
|
|
63
|
+
* JOIN account u ON u.data_seq = o.account_seq
|
|
64
|
+
* WHERE o.status = ?`,
|
|
65
|
+
* params: ["pending"],
|
|
66
|
+
* limit: 100,
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export interface EntityQueryRequest {
|
|
71
|
+
sql: string;
|
|
72
|
+
params?: unknown[];
|
|
73
|
+
limit?: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface RegisterPushDeviceOptions {
|
|
77
|
+
platform?: string;
|
|
78
|
+
deviceType?: string;
|
|
79
|
+
browser?: string;
|
|
80
|
+
browserVersion?: string;
|
|
81
|
+
pushEnabled?: boolean;
|
|
82
|
+
transactionId?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** EntityServerClient 생성/설정 옵션입니다. */
|
|
86
|
+
export interface EntityServerClientOptions {
|
|
87
|
+
baseUrl?: string;
|
|
88
|
+
token?: string;
|
|
89
|
+
packetMagicLen?: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* `list()`, `history()` 응답의 `data` 필드 구조입니다.
|
|
94
|
+
*
|
|
95
|
+
* 서버는 항상 이 구조로 반환합니다:
|
|
96
|
+
* ```json
|
|
97
|
+
* { "ok": true, "data": { "items": [...], "total": 100, "page": 1, "limit": 20 } }
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export interface EntityListResult<T = unknown> {
|
|
101
|
+
items: T[];
|
|
102
|
+
/** 전체 레코드 수 */
|
|
103
|
+
total: number;
|
|
104
|
+
/** 현재 페이지 번호 */
|
|
105
|
+
page: number;
|
|
106
|
+
/** 페이지당 레코드 수 */
|
|
107
|
+
limit: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* `history()` 응답의 개별 이력 레코드 구조입니다.
|
|
112
|
+
*
|
|
113
|
+
* - `action`: `"INSERT"` | `"UPDATE"` | `"DELETE_SOFT"` | `"DELETE_HARD"` | `"ROLLBACK"`
|
|
114
|
+
* - `data_snapshot`: 변경 당시 엔티티 데이터 스냅샷
|
|
115
|
+
*/
|
|
116
|
+
export interface EntityHistoryRecord<T = unknown> {
|
|
117
|
+
seq: number;
|
|
118
|
+
action:
|
|
119
|
+
| "INSERT"
|
|
120
|
+
| "UPDATE"
|
|
121
|
+
| "DELETE_SOFT"
|
|
122
|
+
| "DELETE_HARD"
|
|
123
|
+
| "ROLLBACK"
|
|
124
|
+
| string;
|
|
125
|
+
data_snapshot: T | null;
|
|
126
|
+
changed_by: number | null;
|
|
127
|
+
changed_time: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Vite 환경변수(`import.meta.env`)에서 값을 읽습니다. */
|
|
131
|
+
function readEnv(name: string): string | undefined {
|
|
132
|
+
const meta = import.meta as unknown as {
|
|
133
|
+
env?: Record<string, string | undefined>;
|
|
134
|
+
};
|
|
135
|
+
return meta?.env?.[name];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export class EntityServerClient {
|
|
139
|
+
private baseUrl: string;
|
|
140
|
+
private token: string;
|
|
141
|
+
private packetMagicLen: number;
|
|
142
|
+
private activeTxId: string | null = null;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* EntityServerClient 인스턴스를 생성합니다.
|
|
146
|
+
*
|
|
147
|
+
* 기본값:
|
|
148
|
+
* - `baseUrl`: `VITE_ENTITY_SERVER_URL` 또는 `http://localhost:47200`
|
|
149
|
+
* - `packetMagicLen`: `VITE_PACKET_MAGIC_LEN` 또는 `4`
|
|
150
|
+
*/
|
|
151
|
+
constructor(options: EntityServerClientOptions = {}) {
|
|
152
|
+
const envBaseUrl = readEnv("VITE_ENTITY_SERVER_URL");
|
|
153
|
+
const envMagicLen = readEnv("VITE_PACKET_MAGIC_LEN");
|
|
154
|
+
|
|
155
|
+
this.baseUrl = (
|
|
156
|
+
options.baseUrl ??
|
|
157
|
+
envBaseUrl ??
|
|
158
|
+
"http://localhost:47200"
|
|
159
|
+
).replace(/\/$/, "");
|
|
160
|
+
|
|
161
|
+
this.token = options.token ?? "";
|
|
162
|
+
this.packetMagicLen =
|
|
163
|
+
options.packetMagicLen ?? (envMagicLen ? Number(envMagicLen) : 4);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** baseUrl, token, packetMagicLen 값을 런타임에 갱신합니다. */
|
|
167
|
+
configure(options: Partial<EntityServerClientOptions>): void {
|
|
168
|
+
if (options.baseUrl) {
|
|
169
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
170
|
+
}
|
|
171
|
+
if (typeof options.token === "string") {
|
|
172
|
+
this.token = options.token;
|
|
173
|
+
}
|
|
174
|
+
if (typeof options.packetMagicLen === "number") {
|
|
175
|
+
this.packetMagicLen = options.packetMagicLen;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 인증 요청에 사용할 JWT Access Token을 설정합니다. */
|
|
180
|
+
setToken(token: string): void {
|
|
181
|
+
this.token = token;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 암호화 패킷 magic 길이(`packet_magic_len`)를 설정합니다. */
|
|
185
|
+
setPacketMagicLen(length: number): void {
|
|
186
|
+
this.packetMagicLen = length;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 현재 암호화 패킷 magic 길이를 반환합니다. */
|
|
190
|
+
getPacketMagicLen(): number {
|
|
191
|
+
return this.packetMagicLen;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 로그인 후 `access_token`을 내부 상태에 저장합니다. */
|
|
195
|
+
async login(
|
|
196
|
+
email: string,
|
|
197
|
+
password: string,
|
|
198
|
+
): Promise<{
|
|
199
|
+
access_token: string;
|
|
200
|
+
refresh_token: string;
|
|
201
|
+
expires_in: number;
|
|
202
|
+
}> {
|
|
203
|
+
const data = await this.request<{
|
|
204
|
+
data: {
|
|
205
|
+
access_token: string;
|
|
206
|
+
refresh_token: string;
|
|
207
|
+
expires_in: number;
|
|
208
|
+
};
|
|
209
|
+
}>("POST", "/v1/auth/login", { email, passwd: password }, false);
|
|
210
|
+
this.token = data.data.access_token;
|
|
211
|
+
return data.data;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Refresh Token으로 Access Token을 재발급받아 내부 토큰을 교체합니다. */
|
|
215
|
+
async refreshToken(
|
|
216
|
+
refreshToken: string,
|
|
217
|
+
): Promise<{ access_token: string; expires_in: number }> {
|
|
218
|
+
const data = await this.request<{
|
|
219
|
+
data: { access_token: string; expires_in: number };
|
|
220
|
+
}>("POST", "/v1/auth/refresh", { refresh_token: refreshToken }, false);
|
|
221
|
+
this.token = data.data.access_token;
|
|
222
|
+
return data.data;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 트랜잭션을 시작하고 활성 트랜잭션 ID를 저장합니다. */
|
|
226
|
+
async transStart(): Promise<string> {
|
|
227
|
+
const res = await this.request<{ ok: boolean; transaction_id: string }>(
|
|
228
|
+
"POST",
|
|
229
|
+
"/v1/transaction/start",
|
|
230
|
+
undefined,
|
|
231
|
+
false,
|
|
232
|
+
);
|
|
233
|
+
this.activeTxId = res.transaction_id;
|
|
234
|
+
return this.activeTxId;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** 활성 트랜잭션(또는 전달된 transactionId)을 롤백합니다. */
|
|
238
|
+
transRollback(transactionId?: string): Promise<{ ok: boolean }> {
|
|
239
|
+
const txId = transactionId ?? this.activeTxId;
|
|
240
|
+
if (!txId) {
|
|
241
|
+
return Promise.reject(
|
|
242
|
+
new Error("No active transaction. Call transStart() first."),
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
this.activeTxId = null;
|
|
246
|
+
return this.request("POST", `/v1/transaction/rollback/${txId}`);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 활성 트랜잭션(또는 전달된 transactionId)을 커밋합니다.
|
|
250
|
+
*
|
|
251
|
+
* @returns `results` 배열: commit된 각 작업의 `entity`, `action`, `seq`
|
|
252
|
+
*/
|
|
253
|
+
transCommit(transactionId?: string): Promise<{
|
|
254
|
+
ok: boolean;
|
|
255
|
+
results: Array<{ entity: string; action: string; seq: number }>;
|
|
256
|
+
}> {
|
|
257
|
+
const txId = transactionId ?? this.activeTxId;
|
|
258
|
+
if (!txId) {
|
|
259
|
+
return Promise.reject(
|
|
260
|
+
new Error("No active transaction. Call transStart() first."),
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
this.activeTxId = null;
|
|
264
|
+
return this.request("POST", `/v1/transaction/commit/${txId}`);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 시퀀스 ID로 엔티티 단건을 조회합니다. */
|
|
268
|
+
get<T = unknown>(
|
|
269
|
+
entity: string,
|
|
270
|
+
seq: number,
|
|
271
|
+
opts: { skipHooks?: boolean } = {},
|
|
272
|
+
): Promise<{ ok: boolean; data: T }> {
|
|
273
|
+
const q = opts.skipHooks ? "?skipHooks=true" : "";
|
|
274
|
+
return this.request("GET", `/v1/entity/${entity}/${seq}${q}`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 페이지네이션/정렬/필터 조건으로 엔티티 목록을 조회합니다. */
|
|
278
|
+
list<T = unknown>(
|
|
279
|
+
entity: string,
|
|
280
|
+
params: EntityListParams = {},
|
|
281
|
+
): Promise<{ ok: boolean; data: EntityListResult<T> }> {
|
|
282
|
+
const { conditions, fields, orderDir, orderBy, ...rest } = params;
|
|
283
|
+
|
|
284
|
+
const queryObj: Record<string, unknown> = {
|
|
285
|
+
page: 1,
|
|
286
|
+
limit: 20,
|
|
287
|
+
...rest,
|
|
288
|
+
};
|
|
289
|
+
if (orderBy) {
|
|
290
|
+
queryObj.orderBy = orderDir === "DESC" ? `-${orderBy}` : orderBy;
|
|
291
|
+
}
|
|
292
|
+
if (fields?.length) {
|
|
293
|
+
queryObj.fields = fields.join(",");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const q = buildQuery(queryObj);
|
|
297
|
+
return this.request(
|
|
298
|
+
"POST",
|
|
299
|
+
`/v1/entity/${entity}/list?${q}`,
|
|
300
|
+
conditions ?? {},
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* 엔티티 총 건수를 조회합니다.
|
|
306
|
+
*
|
|
307
|
+
* @param conditions 필터 조건 (예: `{ status: "active" }`)
|
|
308
|
+
*/
|
|
309
|
+
count(
|
|
310
|
+
entity: string,
|
|
311
|
+
conditions?: Record<string, unknown>,
|
|
312
|
+
): Promise<{ ok: boolean; count: number }> {
|
|
313
|
+
return this.request(
|
|
314
|
+
"POST",
|
|
315
|
+
`/v1/entity/${entity}/count`,
|
|
316
|
+
conditions ?? {},
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* 커스텀 SQL로 엔티티를 조회합니다.
|
|
322
|
+
*
|
|
323
|
+
* SELECT 전용이며 인덱스 테이블만 조회 가능합니다.
|
|
324
|
+
* JOIN을 사용해 여러 엔티티를 조합할 수 있습니다.
|
|
325
|
+
* `entity`는 SQL에 포함된 기본 엔티티명(라우트 경로용)입니다.
|
|
326
|
+
*/
|
|
327
|
+
query<T = unknown>(
|
|
328
|
+
entity: string,
|
|
329
|
+
req: EntityQueryRequest,
|
|
330
|
+
): Promise<{ ok: boolean; data: { items: T[]; count: number } }> {
|
|
331
|
+
return this.request("POST", `/v1/entity/${entity}/query`, req);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 엔티티 데이터를 생성/수정(Submit)합니다. `seq`가 없으면 INSERT, 있으면 UPDATE입니다. */
|
|
335
|
+
submit(
|
|
336
|
+
entity: string,
|
|
337
|
+
data: Record<string, unknown>,
|
|
338
|
+
opts: { transactionId?: string; skipHooks?: boolean } = {},
|
|
339
|
+
): Promise<{ ok: boolean; seq: number }> {
|
|
340
|
+
const txId = opts.transactionId ?? this.activeTxId;
|
|
341
|
+
const extraHeaders = txId ? { "X-Transaction-ID": txId } : undefined;
|
|
342
|
+
const q = opts.skipHooks ? "?skipHooks=true" : "";
|
|
343
|
+
|
|
344
|
+
return this.request(
|
|
345
|
+
"POST",
|
|
346
|
+
`/v1/entity/${entity}/submit${q}`,
|
|
347
|
+
data,
|
|
348
|
+
true,
|
|
349
|
+
extraHeaders,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** 시퀀스 ID로 엔티티를 삭제합니다(`hard=true`면 하드 삭제, 기본은 소프트 삭제). */
|
|
354
|
+
delete(
|
|
355
|
+
entity: string,
|
|
356
|
+
seq: number,
|
|
357
|
+
opts: {
|
|
358
|
+
transactionId?: string;
|
|
359
|
+
hard?: boolean;
|
|
360
|
+
skipHooks?: boolean;
|
|
361
|
+
} = {},
|
|
362
|
+
): Promise<{ ok: boolean; deleted: number }> {
|
|
363
|
+
const params = new URLSearchParams();
|
|
364
|
+
if (opts.hard) params.set("hard", "true");
|
|
365
|
+
if (opts.skipHooks) params.set("skipHooks", "true");
|
|
366
|
+
const q = params.size ? `?${params}` : "";
|
|
367
|
+
const txId = opts.transactionId ?? this.activeTxId;
|
|
368
|
+
const extraHeaders = txId ? { "X-Transaction-ID": txId } : undefined;
|
|
369
|
+
|
|
370
|
+
return this.request(
|
|
371
|
+
"POST",
|
|
372
|
+
`/v1/entity/${entity}/delete/${seq}${q}`,
|
|
373
|
+
undefined,
|
|
374
|
+
true,
|
|
375
|
+
extraHeaders,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 엔티티 단건의 변경 이력을 조회합니다. 이력 항목당 `action`, `data_snapshot`, `changed_by`, `changed_time`을 포함합니다. */
|
|
380
|
+
history<T = unknown>(
|
|
381
|
+
entity: string,
|
|
382
|
+
seq: number,
|
|
383
|
+
params: Pick<EntityListParams, "page" | "limit"> = {},
|
|
384
|
+
): Promise<{
|
|
385
|
+
ok: boolean;
|
|
386
|
+
data: EntityListResult<EntityHistoryRecord<T>>;
|
|
387
|
+
}> {
|
|
388
|
+
const q = buildQuery({ page: 1, limit: 50, ...params });
|
|
389
|
+
return this.request("GET", `/v1/entity/${entity}/history/${seq}?${q}`);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 특정 이력 시점으로 엔티티를 롤백합니다. */
|
|
393
|
+
rollback(entity: string, historySeq: number): Promise<{ ok: boolean }> {
|
|
394
|
+
return this.request(
|
|
395
|
+
"POST",
|
|
396
|
+
`/v1/entity/${entity}/rollback/${historySeq}`,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** 푸시 관련 엔티티로 payload를 전송(Submit)합니다. */
|
|
401
|
+
push(
|
|
402
|
+
pushEntity: string,
|
|
403
|
+
payload: Record<string, unknown>,
|
|
404
|
+
opts: { transactionId?: string } = {},
|
|
405
|
+
): Promise<{ ok: boolean; seq: number }> {
|
|
406
|
+
return this.submit(pushEntity, payload, opts);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** 푸시 로그 엔티티 목록을 조회합니다. */
|
|
410
|
+
pushLogList<T = unknown>(
|
|
411
|
+
params: EntityListParams = {},
|
|
412
|
+
): Promise<{ ok: boolean; data: EntityListResult<T> }> {
|
|
413
|
+
return this.list<T>("push_log", params);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** 계정의 푸시 디바이스를 등록합니다. */
|
|
417
|
+
registerPushDevice(
|
|
418
|
+
accountSeq: number,
|
|
419
|
+
deviceId: string,
|
|
420
|
+
pushToken: string,
|
|
421
|
+
opts: RegisterPushDeviceOptions = {},
|
|
422
|
+
): Promise<{ ok: boolean; seq: number }> {
|
|
423
|
+
const {
|
|
424
|
+
platform,
|
|
425
|
+
deviceType,
|
|
426
|
+
browser,
|
|
427
|
+
browserVersion,
|
|
428
|
+
pushEnabled = true,
|
|
429
|
+
transactionId,
|
|
430
|
+
} = opts;
|
|
431
|
+
|
|
432
|
+
return this.submit(
|
|
433
|
+
"account_device",
|
|
434
|
+
{
|
|
435
|
+
id: deviceId,
|
|
436
|
+
account_seq: accountSeq,
|
|
437
|
+
push_token: pushToken,
|
|
438
|
+
push_enabled: pushEnabled,
|
|
439
|
+
...(platform ? { platform } : {}),
|
|
440
|
+
...(deviceType ? { device_type: deviceType } : {}),
|
|
441
|
+
...(browser ? { browser } : {}),
|
|
442
|
+
...(browserVersion ? { browser_version: browserVersion } : {}),
|
|
443
|
+
},
|
|
444
|
+
{ transactionId },
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** 디바이스 레코드의 푸시 토큰을 갱신합니다. */
|
|
449
|
+
updatePushDeviceToken(
|
|
450
|
+
deviceSeq: number,
|
|
451
|
+
pushToken: string,
|
|
452
|
+
opts: { pushEnabled?: boolean; transactionId?: string } = {},
|
|
453
|
+
): Promise<{ ok: boolean; seq: number }> {
|
|
454
|
+
const { pushEnabled = true, transactionId } = opts;
|
|
455
|
+
return this.submit(
|
|
456
|
+
"account_device",
|
|
457
|
+
{
|
|
458
|
+
seq: deviceSeq,
|
|
459
|
+
push_token: pushToken,
|
|
460
|
+
push_enabled: pushEnabled,
|
|
461
|
+
},
|
|
462
|
+
{ transactionId },
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** 디바이스의 푸시 수신을 비활성화합니다. */
|
|
467
|
+
disablePushDevice(
|
|
468
|
+
deviceSeq: number,
|
|
469
|
+
opts: { transactionId?: string } = {},
|
|
470
|
+
): Promise<{ ok: boolean; seq: number }> {
|
|
471
|
+
return this.submit(
|
|
472
|
+
"account_device",
|
|
473
|
+
{
|
|
474
|
+
seq: deviceSeq,
|
|
475
|
+
push_enabled: false,
|
|
476
|
+
},
|
|
477
|
+
{ transactionId: opts.transactionId },
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* 요청 바디를 파싱하고 `application/octet-stream`인 경우 복호화합니다.
|
|
483
|
+
*
|
|
484
|
+
* 원시 암호화 payload를 직접 다루는 클라이언트에서 사용합니다.
|
|
485
|
+
*/
|
|
486
|
+
readRequestBody<T = Record<string, unknown>>(
|
|
487
|
+
body: ArrayBuffer | Uint8Array | string | T | null | undefined,
|
|
488
|
+
contentType = "application/json",
|
|
489
|
+
requireEncrypted = false,
|
|
490
|
+
): T {
|
|
491
|
+
const lowered = contentType.toLowerCase();
|
|
492
|
+
const isEncrypted = lowered.includes("application/octet-stream");
|
|
493
|
+
|
|
494
|
+
if (requireEncrypted && !isEncrypted) {
|
|
495
|
+
throw new Error(
|
|
496
|
+
"Encrypted request required: Content-Type must be application/octet-stream",
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
if (isEncrypted) {
|
|
501
|
+
if (body == null) {
|
|
502
|
+
throw new Error("Encrypted request body is empty");
|
|
503
|
+
}
|
|
504
|
+
if (body instanceof ArrayBuffer) {
|
|
505
|
+
return this.decryptPacket<T>(body);
|
|
506
|
+
}
|
|
507
|
+
if (body instanceof Uint8Array) {
|
|
508
|
+
const sliced = body.buffer.slice(
|
|
509
|
+
body.byteOffset,
|
|
510
|
+
body.byteOffset + body.byteLength,
|
|
511
|
+
);
|
|
512
|
+
return this.decryptPacket<T>(sliced as ArrayBuffer);
|
|
513
|
+
}
|
|
514
|
+
throw new Error(
|
|
515
|
+
"Encrypted request body must be ArrayBuffer or Uint8Array",
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
if (body == null || body === "") return {} as T;
|
|
520
|
+
if (typeof body === "string") return JSON.parse(body) as T;
|
|
521
|
+
return body as T;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* 공통 HTTP 요청 함수입니다.
|
|
526
|
+
*
|
|
527
|
+
* 응답이 `application/octet-stream`이면 자동 복호화하고,
|
|
528
|
+
* JSON 응답의 `ok`가 false이면 에러를 던집니다.
|
|
529
|
+
*/
|
|
530
|
+
private async request<T>(
|
|
531
|
+
method: string,
|
|
532
|
+
path: string,
|
|
533
|
+
body?: unknown,
|
|
534
|
+
withAuth = true,
|
|
535
|
+
extraHeaders: Record<string, string> = {},
|
|
536
|
+
): Promise<T> {
|
|
537
|
+
const headers: Record<string, string> = {
|
|
538
|
+
"Content-Type": "application/json",
|
|
539
|
+
...extraHeaders,
|
|
540
|
+
};
|
|
541
|
+
if (withAuth && this.token) {
|
|
542
|
+
headers.Authorization = `Bearer ${this.token}`;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const res = await fetch(this.baseUrl + path, {
|
|
546
|
+
method,
|
|
547
|
+
headers,
|
|
548
|
+
...(body != null ? { body: JSON.stringify(body) } : {}),
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
const contentType = res.headers.get("Content-Type") ?? "";
|
|
552
|
+
|
|
553
|
+
if (contentType.includes("application/octet-stream")) {
|
|
554
|
+
const buffer = await res.arrayBuffer();
|
|
555
|
+
return this.decryptPacket<T>(buffer);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const data = await res.json();
|
|
559
|
+
if (!data.ok) {
|
|
560
|
+
const err = new Error(
|
|
561
|
+
data.message ?? `EntityServer error (HTTP ${res.status})`,
|
|
562
|
+
);
|
|
563
|
+
(err as { status?: number }).status = res.status;
|
|
564
|
+
throw err;
|
|
565
|
+
}
|
|
566
|
+
return data as T;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** 서버의 암호화 패킷을 복호화해 JSON 객체로 변환합니다. */
|
|
570
|
+
private decryptPacket<T>(buffer: ArrayBuffer): T {
|
|
571
|
+
const key = sha256(new TextEncoder().encode(this.token));
|
|
572
|
+
const data = new Uint8Array(buffer);
|
|
573
|
+
|
|
574
|
+
if (data.length < this.packetMagicLen + 24 + 16) {
|
|
575
|
+
throw new Error("Encrypted packet too short");
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const nonce = data.slice(this.packetMagicLen, this.packetMagicLen + 24);
|
|
579
|
+
const ciphertext = data.slice(this.packetMagicLen + 24);
|
|
580
|
+
const cipher = xchacha20poly1305(key, nonce);
|
|
581
|
+
const plaintext = cipher.decrypt(ciphertext);
|
|
582
|
+
return JSON.parse(new TextDecoder().decode(plaintext)) as T;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** 쿼리 파라미터 객체를 URL 쿼리 문자열로 변환합니다. */
|
|
587
|
+
function buildQuery(params: Record<string, unknown>): string {
|
|
588
|
+
return Object.entries(params)
|
|
589
|
+
.filter(([, value]) => value != null)
|
|
590
|
+
.map(
|
|
591
|
+
([key, value]) =>
|
|
592
|
+
`${encodeURIComponent(key === "orderBy" ? "order_by" : key)}=${encodeURIComponent(String(value))}`,
|
|
593
|
+
)
|
|
594
|
+
.join("&");
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export const entityServer = new EntityServerClient();
|
package/src/react.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./hooks/useEntityServer";
|
package/tsconfig.json
ADDED