feat: Zod를 사용한 월드 상태 구성 및 메타 타입 추가, 사용자 ID 처리 개선

This commit is contained in:
2026-01-05 14:49:19 +00:00
parent 4391110ab0
commit 1861cbc9c6
17 changed files with 118 additions and 153 deletions
+18 -1
View File
@@ -1,3 +1,4 @@
import { z } from 'zod';
import type { GameSessionTokenPayload } from '@sammo-ts/common';
import type { DatabaseClient as InfraDatabaseClient, RedisConnector } from '@sammo-ts/infra';
@@ -10,6 +11,21 @@ export interface GameProfile {
name: string;
}
export const zWorldStateConfig = z.object({
maxUserCnt: z.number().optional(),
fictionMode: z.string().optional(),
});
export type WorldStateConfig = z.infer<typeof zWorldStateConfig>;
export const zWorldStateMeta = z.object({
starttime: z.string().optional(),
opentime: z.string().optional(),
turntime: z.string().optional(),
otherTextInfo: z.string().optional(),
isUnited: z.number().optional(),
});
export type WorldStateMeta = z.infer<typeof zWorldStateMeta>;
export interface WorldStateRow {
scenarioCode: string;
currentYear: number;
@@ -22,7 +38,7 @@ export interface WorldStateRow {
export interface GeneralRow {
id: number;
userId: number | null;
userId: string | null;
name: string;
nationId: number;
cityId: number;
@@ -49,6 +65,7 @@ export interface GeneralRow {
atmos: number;
age: number;
npcState: number;
picture: string | null;
meta: unknown;
}
+21 -14
View File
@@ -1,7 +1,8 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { WorldStateRow } from './context.js';
import { zWorldStateConfig, zWorldStateMeta } from './context.js';
import type { GameApiContext, WorldStateRow } from './context.js';
import { authedProcedure, procedure, router } from './trpc.js';
import { buildTurnCommandTable } from './turns/commandTable.js';
import {
@@ -67,12 +68,12 @@ const toWorldStateSnapshot = (row: WorldStateRow) => ({
updatedAt: row.updatedAt.toISOString(),
});
const getMyGeneral = async (ctx: { db: any, auth: any }) => {
const getMyGeneral = async (ctx: Pick<GameApiContext, 'db' | 'auth'>) => {
if (!ctx.auth?.user.id) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const general = await ctx.db.general.findFirst({
where: { userId: parseInt(ctx.auth.user.id) },
where: { userId: ctx.auth.user.id },
});
if (!general) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'General not found' });
@@ -90,14 +91,20 @@ export const appRouter = router({
}),
lobby: router({
info: procedure.query(async ({ ctx }) => {
const worldState = await ctx.db.worldState.findFirst();
if (!worldState) {
const rawWorldState = await ctx.db.worldState.findFirst();
if (!rawWorldState) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'World state not found',
});
}
const worldState = {
...rawWorldState,
config: zWorldStateConfig.parse(rawWorldState.config),
meta: zWorldStateMeta.parse(rawWorldState.meta),
};
const userCnt = await ctx.db.general.count({ where: { npcState: 0 } });
const npcCnt = await ctx.db.general.count({ where: { npcState: { gt: 0 } } });
const nationCnt = await ctx.db.nation.count({ where: { level: { gt: 0 } } });
@@ -111,8 +118,8 @@ export const appRouter = router({
});
if (general) {
myGeneral = {
name: (general as any).name,
picture: (general as any).picture,
name: general.name,
picture: general.picture,
};
}
}
@@ -121,16 +128,16 @@ export const appRouter = router({
year: worldState.currentYear,
month: worldState.currentMonth,
userCnt,
maxUserCnt: (worldState.config as any).maxUserCnt ?? 500,
maxUserCnt: worldState.config.maxUserCnt ?? 500,
npcCnt,
nationCnt,
turnTerm: worldState.tickSeconds / 60,
fictionMode: (worldState.config as any).fictionMode ?? '사실',
starttime: (worldState.meta as any).starttime ?? '',
opentime: (worldState.meta as any).opentime ?? '',
turntime: (worldState.meta as any).turntime ?? '',
otherTextInfo: (worldState.meta as any).otherTextInfo ?? '',
isUnited: (worldState.meta as any).isUnited ?? 0,
fictionMode: worldState.config.fictionMode ?? '사실',
starttime: worldState.meta.starttime ?? '',
opentime: worldState.meta.opentime ?? '',
turntime: worldState.meta.turntime ?? '',
otherTextInfo: worldState.meta.otherTextInfo ?? '',
isUnited: worldState.meta.isUnited ?? 0,
myGeneral,
};
}),
+1 -1
View File
@@ -84,7 +84,7 @@ export const createGameApiServer = async () => {
const token = extractBearerToken(req.headers.authorization);
const auth = token ? tokenVerifier.verify(token) : null;
return createGameApiContext({
db: postgres.prisma as unknown as DatabaseClient,
db: postgres.prisma,
redis: redis.client,
turnDaemon,
battleSim,
@@ -1,7 +1,6 @@
import {
createGamePostgresConnector,
type InputJsonValue,
type TurnEngineDatabaseClient,
type TurnEngineEventCreateManyInput,
} from '@sammo-ts/infra';
import {
@@ -125,7 +124,7 @@ export const seedScenarioToDatabase = async (
await connector.connect();
try {
const prisma = connector.prisma as unknown as TurnEngineDatabaseClient;
const prisma = connector.prisma;
if (options.resetTables ?? true) {
await prisma.event.deleteMany();
+5 -4
View File
@@ -2,7 +2,6 @@ import {
createGamePostgresConnector,
type InputJsonValue,
type TurnEngineCityUpdateInput,
type TurnEngineDatabaseClient,
type TurnEngineDiplomacyCreateManyInput,
type TurnEngineDiplomacyUpdateInput,
type TurnEngineGeneralCreateManyInput,
@@ -238,7 +237,7 @@ export const createDatabaseTurnHooks = async (
// 턴 처리 결과를 DB에 반영하는 훅을 만든다.
const connector = createGamePostgresConnector({ url: databaseUrl });
await connector.connect();
const prisma = connector.prisma as unknown as TurnEngineDatabaseClient;
const prisma = connector.prisma;
const hooks: TurnDaemonHooks = {
flushChanges: async () => {
@@ -346,8 +345,10 @@ export const createDatabaseTurnHooks = async (
.map((entry) =>
prisma.diplomacy.update({
where: {
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
srcNationId_destNationId: {
srcNationId: entry.fromNationId,
destNationId: entry.toNationId,
},
},
data: buildDiplomacyUpdate(entry),
})
@@ -36,15 +36,6 @@ export interface GatewayAdminActionConsumer {
stop(): Promise<void>;
}
type GatewayProfileRow = {
meta: unknown;
};
type GatewayProfileClient = {
findUnique(args: unknown): Promise<GatewayProfileRow | null>;
update(args: unknown): Promise<void>;
};
const DEFAULT_POLL_MS = 5000;
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -75,9 +66,7 @@ export const createGatewayAdminActionConsumer = async (
url: options.gatewayDatabaseUrl ?? options.databaseUrl,
});
await connector.connect();
const prisma = connector.prisma as unknown as {
gatewayProfile: GatewayProfileClient;
};
const prisma = connector.prisma;
let timer: NodeJS.Timeout | null = null;
let inFlight = false;
+1 -12
View File
@@ -18,15 +18,6 @@ const DEFAULT_CACHE_MS = 2000;
const isRunningStatus = (status: string | null | undefined): boolean =>
status === 'RUNNING';
type GatewayProfileRow = {
status: string | null;
};
type GatewayProfileClient = {
findUnique(args: unknown): Promise<GatewayProfileRow | null>;
update(args: unknown): Promise<void>;
};
export const createGatewayProfileGate = async (
options: GatewayProfileGateOptions
): Promise<GatewayProfileGate> => {
@@ -34,9 +25,7 @@ export const createGatewayProfileGate = async (
url: options.gatewayDatabaseUrl ?? options.databaseUrl,
});
await connector.connect();
const prisma = connector.prisma as unknown as {
gatewayProfile: GatewayProfileClient;
};
const prisma = connector.prisma;
let lastCheckedAt = 0;
let cachedPause = false;
@@ -272,7 +272,7 @@ export const createReservedTurnStore = async (
const connector = createGamePostgresConnector({ url: options.databaseUrl });
await connector.connect();
const store = new InMemoryReservedTurnStore(
connector.prisma as unknown as ReservedTurnDatabaseClient,
connector.prisma,
{
maxGeneralTurns: options.maxGeneralTurns ?? DEFAULT_GENERAL_TURNS,
maxNationTurns: options.maxNationTurns ?? DEFAULT_NATION_TURNS,
+1 -1
View File
@@ -255,7 +255,7 @@ export const loadTurnWorldFromDatabase = async (
const connector = createGamePostgresConnector({ url: options.databaseUrl });
await connector.connect();
try {
const prisma = connector.prisma as unknown as TurnEngineDatabaseClient;
const prisma: TurnEngineDatabaseClient = connector.prisma;
const worldState = await prisma.worldState.findFirst();
if (!worldState) {
throw new Error('world_state row is required to start turn daemon.');
@@ -74,7 +74,7 @@ export class RepositoryProfileStatusService implements GatewayProfileStatusServi
row: GatewayProfileRecord,
runtimeMap: Map<string, { apiRunning: boolean; daemonRunning: boolean }>
): LobbyProfileStatus {
const meta = row.meta as Record<string, any>;
const meta = row.meta;
return {
profileName: row.profileName,
profile: row.profile,
@@ -85,8 +85,8 @@ export class RepositoryProfileStatusService implements GatewayProfileStatusServi
apiRunning: false,
daemonRunning: false,
},
korName: (meta.korName as string) ?? row.profile,
color: (meta.color as string) ?? '#ffffff',
korName: (meta.korName as string | undefined) ?? row.profile,
color: (meta.color as string | undefined) ?? '#ffffff',
};
}
}
@@ -587,15 +587,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
const connector = createGamePostgresConnector({ url: databaseUrl });
await connector.connect();
try {
const prisma = connector.prisma as unknown as {
worldState: {
findFirst: (args: unknown) => Promise<{
scenarioCode: string | null;
tickSeconds: number | null;
} | null>;
};
};
const row = await prisma.worldState.findFirst({
const row = await connector.prisma.worldState.findFirst({
select: { scenarioCode: true, tickSeconds: true },
});
if (row) {
@@ -122,15 +122,6 @@ type GatewayProfileRow = {
updatedAt: Date;
};
type GatewayProfileClient = {
findMany(args: unknown): Promise<GatewayProfileRow[]>;
findUnique(args: unknown): Promise<GatewayProfileRow | null>;
findFirst(args: unknown): Promise<GatewayProfileRow | null>;
upsert(args: unknown): Promise<GatewayProfileRow>;
update(args: unknown): Promise<GatewayProfileRow>;
updateMany(args: unknown): Promise<unknown>;
};
const mapProfile = (row: GatewayProfileRow): GatewayProfileRecord => ({
profileName: row.profileName,
profile: row.profile,
@@ -161,23 +152,20 @@ export const createGatewayProfileRepository = (
prisma: GatewayPrismaClient
): GatewayProfileRepository => ({
async listProfiles(): Promise<GatewayProfileRecord[]> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const rows = await gatewayProfile.findMany({
const rows = await prisma.gatewayProfile.findMany({
orderBy: [{ profile: 'asc' }, { scenario: 'asc' }],
});
return rows.map(mapProfile);
},
async getProfile(profileName: string): Promise<GatewayProfileRecord | null> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const row = await gatewayProfile.findUnique({
const row = await prisma.gatewayProfile.findUnique({
where: { profileName },
});
return row ? mapProfile(row) : null;
},
async upsertProfile(input: GatewayProfileUpsertInput): Promise<GatewayProfileRecord> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const profileName = buildProfileName(input.profile, input.scenario);
const row = await gatewayProfile.upsert({
const row = await prisma.gatewayProfile.upsert({
where: { profileName },
create: {
profileName,
@@ -229,7 +217,7 @@ export const createGatewayProfileRepository = (
scheduledStartAt?: string | null;
}
): Promise<GatewayProfileRecord | null> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
const row = await gatewayProfile.update({
where: { profileName },
data: {
@@ -269,7 +257,7 @@ export const createGatewayProfileRepository = (
lastUsedAt?: string | null;
}
): Promise<GatewayProfileRecord | null> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
const row = await gatewayProfile.update({
where: { profileName },
data: {
@@ -311,7 +299,7 @@ export const createGatewayProfileRepository = (
profileName: string,
meta: Record<string, unknown>
): Promise<GatewayProfileRecord | null> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
const row = await gatewayProfile.update({
where: { profileName },
data: {
@@ -321,7 +309,7 @@ export const createGatewayProfileRepository = (
return row ? mapProfile(row) : null;
},
async listReservedToStart(now: Date): Promise<GatewayProfileRecord[]> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
const rows = await gatewayProfile.findMany({
where: {
status: 'RESERVED',
@@ -333,7 +321,7 @@ export const createGatewayProfileRepository = (
return rows.map(mapProfile);
},
async findQueuedBuild(): Promise<GatewayProfileRecord | null> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
const row = await gatewayProfile.findFirst({
where: { buildStatus: 'QUEUED' },
orderBy: { buildRequestedAt: 'asc' },
@@ -341,7 +329,7 @@ export const createGatewayProfileRepository = (
return row ? mapProfile(row) : null;
},
async updateLastError(profileName: string, lastError: string | null): Promise<void> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
await gatewayProfile.update({
where: { profileName },
data: { lastError },
@@ -352,7 +340,7 @@ export const createGatewayProfileRepository = (
workspace: string,
lastUsedAt: string
): Promise<void> {
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
await gatewayProfile.update({
where: { profileName },
data: {
@@ -365,7 +353,7 @@ export const createGatewayProfileRepository = (
if (!profileNames.length) {
return;
}
const gatewayProfile = prisma.gatewayProfile as unknown as GatewayProfileClient;
const gatewayProfile = prisma.gatewayProfile;
await gatewayProfile.updateMany({
where: {
profileName: { in: profileNames },
+9 -2
View File
@@ -1,11 +1,18 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
export interface UserInfo {
id: string;
username: string;
displayName: string;
roles: string[];
}
export const useAuthStore = defineStore('auth', () => {
const user = ref(null);
const user = ref<UserInfo | null>(null);
const isLoggedIn = ref(false);
function setUser(userData: any) {
function setUser(userData: UserInfo | null) {
user.value = userData;
isLoggedIn.value = !!userData;
}