sonamu 0.13.9 → 0.13.11
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/dist/database/base-model.d.ts +5 -8
- package/dist/database/base-model.d.ts.map +1 -1
- package/dist/database/base-model.js +56 -24
- package/dist/database/puri.d.ts +1 -2
- package/dist/database/puri.d.ts.map +1 -1
- package/dist/database/puri.js +65 -58
- package/dist/entity/entity.d.ts +13 -1
- package/dist/entity/entity.d.ts.map +1 -1
- package/dist/entity/entity.js +41 -3
- package/dist/syncer/api-parser.js +6 -1
- package/package.json +1 -1
- package/src/database/__tests__/puri-hydration.test.ts +113 -76
- package/src/database/base-model.ts +75 -43
- package/src/database/puri.ts +84 -106
- package/src/entity/__tests__/entity-subset-query.test.ts +35 -0
- package/src/entity/entity.ts +58 -2
- package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
- package/src/syncer/api-parser.ts +12 -0
package/src/database/puri.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
/* oxlint-disable @typescript-eslint/no-explicit-any */ // Puri는 다양한 타입을 사용하고 있습니다.
|
|
2
2
|
|
|
3
3
|
import assert from "assert";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { type EventEmitter } from "node:events";
|
|
6
4
|
|
|
7
5
|
import chalk from "chalk";
|
|
8
6
|
import inflection from "inflection";
|
|
@@ -199,30 +197,73 @@ type SelectResultValue =
|
|
|
199
197
|
type SelectRow = { [column: string]: SelectResultValue };
|
|
200
198
|
type SelectResult = SelectRow | SelectRow[] | undefined;
|
|
201
199
|
|
|
202
|
-
|
|
203
|
-
|
|
200
|
+
type SelectGroupRule = {
|
|
201
|
+
/** LEFT JOIN 때문에 비어 있을 수 있어 `id`로 null을 판정하는 그룹 */
|
|
202
|
+
nullable: boolean;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 중첩 select 그룹마다 null 판정 규칙을 정하고, 판정할 수 없는 모양이면 오류를 냅니다.
|
|
207
|
+
*
|
|
208
|
+
* - 그룹 경로가 LEFT JOIN 별칭이거나 그룹 칸이 LEFT JOIN 별칭을 가리키면, 그 그룹의 `id`가
|
|
209
|
+
* null인지로만 그룹 전체가 null인지 판정합니다. 그래서 그런 그룹에는 `id`가 있어야 합니다.
|
|
210
|
+
* - 서브쿼리를 LEFT JOIN한 별칭도 같습니다. 서브쿼리가 `id`를 골라 와야 중첩 그룹으로 고를 수 있습니다.
|
|
211
|
+
* - `rawQuery().joinRaw()`처럼 Puri가 모르게 붙인 별칭은 조인 종류를 알 수 없으므로, 그룹에 `id`가
|
|
212
|
+
* 있으면 그 `id`가 null일 때 null로 판정하고 `id`가 없으면 그대로 객체로 둡니다.
|
|
213
|
+
* - 칸이 전부 raw 식이면 별칭을 알 수 없으므로 판정하지 않고 늘 객체로 둡니다.
|
|
214
|
+
*/
|
|
215
|
+
function resolveSelectGroupRules(
|
|
216
|
+
paths: ReadonlyMap<string, readonly string[]>,
|
|
217
|
+
sources: ReadonlyMap<string, string | null>,
|
|
204
218
|
correlations: ReadonlyMap<string, CorrelationRegistration>,
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
219
|
+
): Map<string, SelectGroupRule> {
|
|
220
|
+
const groups = new Map<string, { aliases: Set<string>; hasLeaf: boolean; hasId: boolean }>();
|
|
221
|
+
for (const [key, path] of paths) {
|
|
222
|
+
for (let length = 1; length < path.length; length++) {
|
|
223
|
+
const groupPath = path.slice(0, length).join("__");
|
|
224
|
+
let group = groups.get(groupPath);
|
|
225
|
+
if (group === undefined) {
|
|
226
|
+
group = { aliases: new Set(), hasLeaf: false, hasId: false };
|
|
227
|
+
groups.set(groupPath, group);
|
|
228
|
+
}
|
|
229
|
+
if (length === path.length - 1) {
|
|
230
|
+
group.hasLeaf = true;
|
|
231
|
+
group.hasId ||= path[length] === "id";
|
|
232
|
+
const alias = sources.get(key);
|
|
233
|
+
if (alias !== undefined && alias !== null) group.aliases.add(alias);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const rules = new Map<string, SelectGroupRule>();
|
|
239
|
+
for (const [groupPath, group] of groups) {
|
|
240
|
+
if (group.hasLeaf && group.aliases.size === 0) {
|
|
241
|
+
rules.set(groupPath, { nullable: false });
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const leftJoins = [...new Set([groupPath, ...group.aliases])].flatMap((alias) => {
|
|
245
|
+
const relation = correlations.get(alias);
|
|
246
|
+
return relation?.kind === "join" && relation.joinType === "leftJoin" ? [relation] : [];
|
|
247
|
+
});
|
|
248
|
+
if (leftJoins.length > 0 && !group.hasId) {
|
|
249
|
+
const aliases = leftJoins.map((relation) => `"${relation.alias}"`).join(", ");
|
|
250
|
+
throw new Error(
|
|
251
|
+
`Nested select group "${groupPath}" needs an "id" field because it reads LEFT JOIN ${aliases}. Select the id of that alias in the group, or select its columns flat instead.`,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
const unregistered = [...group.aliases].some((alias) => !correlations.has(alias));
|
|
255
|
+
rules.set(groupPath, { nullable: leftJoins.length > 0 || (group.hasId && unregistered) });
|
|
256
|
+
}
|
|
257
|
+
return rules;
|
|
214
258
|
}
|
|
215
259
|
|
|
216
260
|
function hydrateSelectResult(
|
|
217
261
|
result: SelectResult,
|
|
218
262
|
paths: ReadonlyMap<string, readonly string[]>,
|
|
219
|
-
|
|
220
|
-
presenceColumns: ReadonlyMap<string, string>,
|
|
221
|
-
identitySources: ReadonlyMap<string, string>,
|
|
263
|
+
rules: ReadonlyMap<string, SelectGroupRule>,
|
|
222
264
|
): SelectResult {
|
|
223
265
|
if (paths.size === 0 || result === undefined) return result;
|
|
224
266
|
|
|
225
|
-
const hiddenColumns = new Set(presenceColumns.values());
|
|
226
267
|
const projection: SelectProjection = new Map();
|
|
227
268
|
for (const [alias, path] of paths) {
|
|
228
269
|
let parent = projection;
|
|
@@ -250,24 +291,12 @@ function hydrateSelectResult(
|
|
|
250
291
|
}
|
|
251
292
|
}
|
|
252
293
|
const value = Object.fromEntries(entries);
|
|
253
|
-
//
|
|
254
|
-
|
|
255
|
-
const presenceColumn =
|
|
256
|
-
relationAlias === undefined ? undefined : presenceColumns.get(relationAlias);
|
|
257
|
-
if (
|
|
258
|
-
relationAlias !== undefined &&
|
|
259
|
-
(presenceColumn !== undefined
|
|
260
|
-
? row[presenceColumn] === false
|
|
261
|
-
: Object.hasOwn(value, "id") && value.id === null)
|
|
262
|
-
) {
|
|
263
|
-
return null;
|
|
264
|
-
}
|
|
294
|
+
// LEFT JOIN 그룹은 id가 null일 때만 관계가 비었다고 봅니다.
|
|
295
|
+
if (rules.get(path.join("__"))?.nullable === true && value.id === null) return null;
|
|
265
296
|
return value;
|
|
266
297
|
};
|
|
267
298
|
return {
|
|
268
|
-
...Object.fromEntries(
|
|
269
|
-
Object.entries(row).filter(([key]) => !paths.has(key) && !hiddenColumns.has(key)),
|
|
270
|
-
),
|
|
299
|
+
...Object.fromEntries(Object.entries(row).filter(([key]) => !paths.has(key))),
|
|
271
300
|
...Object.fromEntries(
|
|
272
301
|
[...projection].map(([key, fields]) => {
|
|
273
302
|
assert(fields instanceof Map);
|
|
@@ -285,7 +314,8 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
285
314
|
private knexQuery: Knex.QueryBuilder;
|
|
286
315
|
private tableSpec: TableSpec | null = null;
|
|
287
316
|
private nestedSelectPaths = new Map<string, readonly string[]>();
|
|
288
|
-
|
|
317
|
+
// 중첩 select 칸이 가리키는 별칭(raw 식이면 null)
|
|
318
|
+
private nestedSelectSources = new Map<string, string | null>();
|
|
289
319
|
private correlationRegistry = new Map<string, CorrelationRegistration>();
|
|
290
320
|
|
|
291
321
|
// 생성자 시그니처들
|
|
@@ -727,11 +757,17 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
727
757
|
if (isNestedSelectObject(value)) {
|
|
728
758
|
yield* this.flattenSelectEntries(value, fieldPath);
|
|
729
759
|
} else {
|
|
730
|
-
if (fieldPath.length > 1)
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
760
|
+
if (fieldPath.length > 1) {
|
|
761
|
+
this.nestedSelectPaths.set(fullKey, fieldPath);
|
|
762
|
+
this.nestedSelectSources.set(
|
|
763
|
+
fullKey,
|
|
764
|
+
isStringValue(value) && value.includes(".")
|
|
765
|
+
? value.slice(0, value.lastIndexOf("."))
|
|
766
|
+
: null,
|
|
767
|
+
);
|
|
768
|
+
} else {
|
|
769
|
+
this.nestedSelectPaths.delete(fullKey);
|
|
770
|
+
this.nestedSelectSources.delete(fullKey);
|
|
735
771
|
}
|
|
736
772
|
yield [fullKey, value];
|
|
737
773
|
}
|
|
@@ -791,7 +827,7 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
791
827
|
this.knexQuery.clear(statement);
|
|
792
828
|
if (statement === "select" || statement === "columns") {
|
|
793
829
|
this.nestedSelectPaths.clear();
|
|
794
|
-
this.
|
|
830
|
+
this.nestedSelectSources.clear();
|
|
795
831
|
}
|
|
796
832
|
if (statement === "join") {
|
|
797
833
|
this.clearJoinRegistrations();
|
|
@@ -1596,74 +1632,16 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
1596
1632
|
return this;
|
|
1597
1633
|
}
|
|
1598
1634
|
|
|
1599
|
-
private executeSelect(): Promise<SelectResult> {
|
|
1635
|
+
private async executeSelect(): Promise<SelectResult> {
|
|
1600
1636
|
if (this.nestedSelectPaths.size === 0) return this.knexQuery.then();
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
for (const path of this.nestedSelectPaths.values()) {
|
|
1607
|
-
for (let length = 1; length < path.length; length++) {
|
|
1608
|
-
const alias = getSelectRelationAlias(
|
|
1609
|
-
path.slice(0, length).join("__"),
|
|
1610
|
-
this.correlationRegistry,
|
|
1611
|
-
this.nestedSelectIdentitySources,
|
|
1612
|
-
);
|
|
1613
|
-
if (alias === undefined || presenceColumns.has(alias)) continue;
|
|
1614
|
-
let column: string;
|
|
1615
|
-
do {
|
|
1616
|
-
column = `__sonamu_presence_${randomUUID().replaceAll("-", "")}`;
|
|
1617
|
-
} while (sql.includes(column));
|
|
1618
|
-
if (presenceColumns.size === 0) {
|
|
1619
|
-
executable = this.knexQuery.clone();
|
|
1620
|
-
// Knex.clone이 복제하지 않는 실행 제한과 이벤트는 원본의 계약을 유지합니다.
|
|
1621
|
-
// SAFETY: timeout은 Knex QueryBuilder가 보관하는 실행 옵션입니다.
|
|
1622
|
-
const timeout = (this.knexQuery as any)._timeout;
|
|
1623
|
-
if (isNumberValue(timeout)) {
|
|
1624
|
-
// SAFETY: cancelOnTimeout은 timeout 옵션과 함께 Knex가 기록하는 불리언입니다.
|
|
1625
|
-
executable.timeout(timeout, {
|
|
1626
|
-
cancel: (this.knexQuery as any)._cancelOnTimeout === true,
|
|
1627
|
-
});
|
|
1628
|
-
}
|
|
1629
|
-
// SAFETY: Knex QueryBuilder는 EventEmitter를 상속하지만 공개 타입에는 일부 메서드만 있습니다.
|
|
1630
|
-
const emitter = this.knexQuery as Knex.QueryBuilder & EventEmitter;
|
|
1631
|
-
// SAFETY: 실행 복제본도 동일한 Knex EventEmitter 구현입니다.
|
|
1632
|
-
const executionEmitter: EventEmitter = executable as Knex.QueryBuilder & EventEmitter;
|
|
1633
|
-
for (const event of emitter.eventNames()) {
|
|
1634
|
-
executionEmitter.on(event, (...args: any[]) => emitter.emit(event, ...args));
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
presenceColumns.set(alias, column);
|
|
1638
|
-
executable.select(this.knex.raw("??.* IS DISTINCT FROM NULL AS ??", [alias, column]));
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
return executable.then((result) =>
|
|
1643
|
-
hydrateSelectResult(
|
|
1644
|
-
result,
|
|
1645
|
-
this.nestedSelectPaths,
|
|
1646
|
-
this.correlationRegistry,
|
|
1647
|
-
presenceColumns,
|
|
1648
|
-
this.nestedSelectIdentitySources,
|
|
1649
|
-
),
|
|
1637
|
+
// select와 join이 모두 정해진 실행 시점에 그룹 규칙을 정합니다.
|
|
1638
|
+
const rules = resolveSelectGroupRules(
|
|
1639
|
+
this.nestedSelectPaths,
|
|
1640
|
+
this.nestedSelectSources,
|
|
1641
|
+
this.correlationRegistry,
|
|
1650
1642
|
);
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
private canSelectRelationPresence(): boolean {
|
|
1654
|
-
// 그룹·집계·DISTINCT·원시 표현식에는 열을 추가하면 SQL 의미가 바뀔 수 있습니다.
|
|
1655
|
-
// SAFETY: Knex의 statement 구조는 다른 JOIN/벡터 처리와 동일한 내부 계약으로 읽습니다.
|
|
1656
|
-
const statements = (this.knexQuery as any)._statements;
|
|
1657
|
-
return statements.every((statement: any) => {
|
|
1658
|
-
if (["group", "having", "union"].includes(statement.grouping)) return false;
|
|
1659
|
-
if (statement.grouping !== "columns") return true;
|
|
1660
|
-
if (statement.distinct || statement.distinctOn || statement.type) return false;
|
|
1661
|
-
return statement.value.every((column: string | { ref?: string }) =>
|
|
1662
|
-
isStringValue(column)
|
|
1663
|
-
? !column.includes("*")
|
|
1664
|
-
: isObjectValue(column) && isStringValue(column.ref),
|
|
1665
|
-
);
|
|
1666
|
-
});
|
|
1643
|
+
const result = await this.knexQuery.then();
|
|
1644
|
+
return hydrateSelectResult(result, this.nestedSelectPaths, rules);
|
|
1667
1645
|
}
|
|
1668
1646
|
|
|
1669
1647
|
// 실행 메서드들 - thenable 구현
|
|
@@ -1816,7 +1794,7 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
1816
1794
|
newPuri.knexQuery = this.knexQuery.clone();
|
|
1817
1795
|
newPuri.tableSpec = this.tableSpec;
|
|
1818
1796
|
newPuri.nestedSelectPaths = new Map(this.nestedSelectPaths);
|
|
1819
|
-
newPuri.
|
|
1797
|
+
newPuri.nestedSelectSources = new Map(this.nestedSelectSources);
|
|
1820
1798
|
newPuri.correlationRegistry = new Map(this.correlationRegistry);
|
|
1821
1799
|
return newPuri;
|
|
1822
1800
|
}
|
|
@@ -11,6 +11,14 @@ const chatRoomJson: EntityJson = {
|
|
|
11
11
|
{ name: "id", type: "integer", desc: "ID" },
|
|
12
12
|
{ name: "name", type: "string", desc: "이름" },
|
|
13
13
|
{ name: "case", type: "relation", relationType: "BelongsToOne", with: "Case", desc: "케이스" },
|
|
14
|
+
{
|
|
15
|
+
name: "owned_cases",
|
|
16
|
+
type: "relation",
|
|
17
|
+
relationType: "HasMany",
|
|
18
|
+
with: "Case",
|
|
19
|
+
joinColumn: "owner_id",
|
|
20
|
+
desc: "소유 케이스",
|
|
21
|
+
},
|
|
14
22
|
],
|
|
15
23
|
indexes: [],
|
|
16
24
|
subsets: {},
|
|
@@ -80,4 +88,31 @@ describe("Entity.resolveSubsetQuery", () => {
|
|
|
80
88
|
expect(result.select).toEqual(["cases.owner_id"]);
|
|
81
89
|
expect(result.joins).toEqual([]);
|
|
82
90
|
});
|
|
91
|
+
|
|
92
|
+
it("JOIN으로 붙는 관계 그룹에 id가 없으면 계산된 internal id로 넣고 subsetsInternal에는 쓰지 않는다", () => {
|
|
93
|
+
const caseEntity = setup();
|
|
94
|
+
caseEntity.subsets = {
|
|
95
|
+
A: ["id", "owner.name", "owner.case.id", "chat_room.id"],
|
|
96
|
+
B: ["owner.id", "owner.name"],
|
|
97
|
+
};
|
|
98
|
+
caseEntity.subsetsInternal = { A: [], B: [] };
|
|
99
|
+
|
|
100
|
+
expect(caseEntity.getSubsetAutoInternalFields("A")).toEqual(["owner.id"]);
|
|
101
|
+
expect(caseEntity.getSubsetFieldsForQuery("A")).toContain("owner.id");
|
|
102
|
+
expect(caseEntity.getSubsetAutoInternalFields("B")).toEqual([]);
|
|
103
|
+
expect(caseEntity.subsetsInternal).toEqual({ A: [], B: [] });
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("로더 부모 줄에는 refId 칸을, 로더 줄의 관계 그룹에는 id를 넣는다", () => {
|
|
107
|
+
const caseEntity = setup();
|
|
108
|
+
const chatRoom = EntityManager.get("ChatRoom");
|
|
109
|
+
chatRoom.subsets = { A: ["name", "owned_cases.owner.name"] };
|
|
110
|
+
chatRoom.subsetsInternal = { A: [] };
|
|
111
|
+
caseEntity.subsets = { A: ["owner.owned_cases.id"] };
|
|
112
|
+
caseEntity.subsetsInternal = { A: [] };
|
|
113
|
+
|
|
114
|
+
expect(chatRoom.getSubsetAutoInternalFields("A")).toEqual(["id", "owned_cases.owner.id"]);
|
|
115
|
+
// 로더가 owner__id로 자식을 붙이므로 owner 그룹의 id 하나로 둘 다 충족합니다.
|
|
116
|
+
expect(caseEntity.getSubsetAutoInternalFields("A")).toEqual(["owner.id"]);
|
|
117
|
+
});
|
|
83
118
|
});
|
package/src/entity/entity.ts
CHANGED
|
@@ -179,10 +179,66 @@ export class Entity {
|
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
/**
|
|
182
|
-
* 쿼리용 서브셋 필드를 반환합니다 (subsets + subsetsInternal
|
|
182
|
+
* 쿼리용 서브셋 필드를 반환합니다 (subsets + subsetsInternal + 자동 internal id)
|
|
183
183
|
*/
|
|
184
184
|
getSubsetFieldsForQuery(subsetKey: string): string[] {
|
|
185
|
-
|
|
185
|
+
const fields = [...(this.subsets[subsetKey] ?? []), ...(this.subsetsInternal[subsetKey] ?? [])];
|
|
186
|
+
return [...fields, ...this.getRequiredIdFields(fields)];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 서브셋 쿼리에 자동으로 넣고 결과에서는 지우는 id 필드를 반환합니다.
|
|
191
|
+
* 계산 값이라 subsetsInternal에 쓰지 않습니다(entity.json으로 되써지지 않도록).
|
|
192
|
+
*/
|
|
193
|
+
getSubsetAutoInternalFields(subsetKey: string): string[] {
|
|
194
|
+
return this.getRequiredIdFields([
|
|
195
|
+
...(this.subsets[subsetKey] ?? []),
|
|
196
|
+
...(this.subsetsInternal[subsetKey] ?? []),
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 주어진 필드에 없지만 결과를 접는 데 필요한 id 필드를 계산합니다.
|
|
202
|
+
*
|
|
203
|
+
* - JOIN으로 붙는 -One 관계 그룹마다 `<그룹>.id`: Puri가 그 id로만 관계가 비었는지 판정합니다.
|
|
204
|
+
* - -Many 관계를 가진 줄마다 로더 refId가 가리키는 칸(`id` 또는 fromColumn): 로더가 그 값으로 자식을 붙입니다.
|
|
205
|
+
*/
|
|
206
|
+
private getRequiredIdFields(fields: string[]): string[] {
|
|
207
|
+
const ownFields = new Set(fields.filter((field) => !field.includes(".")));
|
|
208
|
+
const required: string[] = [];
|
|
209
|
+
const requireOwn = (field: string) => {
|
|
210
|
+
if (!ownFields.has(field) && !required.includes(field)) required.push(field);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const relationGroups = group(
|
|
214
|
+
fields.filter((field) => field.includes(".")),
|
|
215
|
+
(field) => field.slice(0, field.indexOf(".")),
|
|
216
|
+
);
|
|
217
|
+
for (const [groupKey, groupedFields = []] of Object.entries(relationGroups)) {
|
|
218
|
+
const relation = this.relations[groupKey];
|
|
219
|
+
// 없는 관계는 resolveSubsetQuery가 오류를 냅니다.
|
|
220
|
+
if (relation === undefined) continue;
|
|
221
|
+
const relFields = groupedFields.map((field) => field.slice(field.indexOf(".") + 1));
|
|
222
|
+
const relEntity = EntityManager.get(relation.with);
|
|
223
|
+
|
|
224
|
+
if (isOneToOneRelationProp(relation) || isBelongsToOneRelationProp(relation)) {
|
|
225
|
+
// id 단독 지름길(JOIN 없이 FK만 고름)은 그대로 둡니다.
|
|
226
|
+
const isIdShortcut =
|
|
227
|
+
relFields.length === 1 &&
|
|
228
|
+
relFields[0] === "id" &&
|
|
229
|
+
!(isOneToOneRelationProp(relation) && !relation.hasJoinColumn);
|
|
230
|
+
if (isIdShortcut) continue;
|
|
231
|
+
const nested = relEntity.getRequiredIdFields(relFields);
|
|
232
|
+
const relRequired = relFields.includes("id") || nested.includes("id") ? [] : ["id"];
|
|
233
|
+
required.push(...[...relRequired, ...nested].map((field) => `${groupKey}.${field}`));
|
|
234
|
+
} else if (isHasManyRelationProp(relation) || isManyToManyRelationProp(relation)) {
|
|
235
|
+
requireOwn(isHasManyRelationProp(relation) ? (relation.fromColumn ?? "id") : "id");
|
|
236
|
+
required.push(
|
|
237
|
+
...relEntity.getRequiredIdFields(relFields).map((field) => `${groupKey}.${field}`),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return required;
|
|
186
242
|
}
|
|
187
243
|
|
|
188
244
|
/**
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "fs/promises";
|
|
2
|
+
import { tmpdir } from "os";
|
|
3
|
+
import path from "path";
|
|
4
|
+
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
6
|
+
|
|
7
|
+
import { registeredApis } from "../../api/decorators";
|
|
8
|
+
import { type AbsolutePath } from "../../utils/path-utils";
|
|
9
|
+
import { readApisFromFile } from "../api-parser";
|
|
10
|
+
|
|
11
|
+
describe("readApisFromFile readonly 타입 연산자", () => {
|
|
12
|
+
let originalApis: Array<(typeof registeredApis)[number]> = [];
|
|
13
|
+
let tempDir: string | null = null;
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
originalApis = [...registeredApis];
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
afterEach(async () => {
|
|
20
|
+
registeredApis.splice(0, registeredApis.length, ...originalApis);
|
|
21
|
+
if (tempDir) {
|
|
22
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
23
|
+
tempDir = null;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("readonly 배열·튜플 파라미터를 내부 타입으로 풀어낸다", async () => {
|
|
28
|
+
registeredApis.push({
|
|
29
|
+
modelName: "RoModel",
|
|
30
|
+
methodName: "foo",
|
|
31
|
+
path: "/ro/foo",
|
|
32
|
+
options: { httpMethod: "POST" },
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
tempDir = await mkdtemp(path.join(tmpdir(), "sonamu-api-parser-"));
|
|
36
|
+
const filePath: AbsolutePath = `/${path.relative("/", path.join(tempDir, "ro.model.ts"))}`;
|
|
37
|
+
await writeFile(
|
|
38
|
+
filePath,
|
|
39
|
+
`
|
|
40
|
+
class RoModelClass {
|
|
41
|
+
@api({ httpMethod: "POST" })
|
|
42
|
+
async foo(ids: readonly number[], pair: readonly [string, number]): Promise<number> {
|
|
43
|
+
return 1;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
`,
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
const [api] = await readApisFromFile(filePath);
|
|
50
|
+
expect(api?.parameters.map((p) => p.type)).toEqual([
|
|
51
|
+
{ t: "array", elementsType: "number" },
|
|
52
|
+
{ t: "tuple-type", elements: ["string", "number"] },
|
|
53
|
+
]);
|
|
54
|
+
});
|
|
55
|
+
});
|
package/src/syncer/api-parser.ts
CHANGED
|
@@ -372,6 +372,18 @@ function resolveTypeNode(typeNode: ts.TypeNode): ApiParamType {
|
|
|
372
372
|
};
|
|
373
373
|
}
|
|
374
374
|
break;
|
|
375
|
+
case ts.SyntaxKind.TypeOperator: {
|
|
376
|
+
// readonly T[] / readonly [A, B] 는 런타임 검증·클라이언트 타입에 영향이 없으므로 내부 타입으로 풀어낸다.
|
|
377
|
+
// (가변 배열은 readonly 배열 파라미터에 그대로 대입 가능)
|
|
378
|
+
const opNode =
|
|
379
|
+
/* SAFETY: TypeScript AST 파싱과 동기화 입력 계약이 이 값의 타입을 보장한다. */ typeNode as ts.TypeOperatorNode;
|
|
380
|
+
if (opNode.operator === ts.SyntaxKind.ReadonlyKeyword) {
|
|
381
|
+
return resolveTypeNode(opNode.type);
|
|
382
|
+
}
|
|
383
|
+
throw new Error(
|
|
384
|
+
`지원하지 않는 타입 연산자 ${ts.tokenToString(opNode.operator)} (API 파라미터에는 keyof/unique 를 쓸 수 없습니다)`,
|
|
385
|
+
);
|
|
386
|
+
}
|
|
375
387
|
case ts.SyntaxKind.ParenthesizedType:
|
|
376
388
|
// 괄호로 묶인 타입 (예: (A & B)[] 에서 (A & B))
|
|
377
389
|
// 내부 타입을 재귀적으로 resolve
|