chore(env): rename test environment to staging
This commit is contained in:
1 parent
d0d578b2b0
commit
eadae789c8
17 files changed
+146
-93
No files matched your search
@@ -86,7 +86,7 @@ pnpm dev:web
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm --filter api test
|
pnpm --filter api test
|
||||||
pnpm --filter web build:test
|
pnpm --filter web build:staging
|
||||||
```
|
```
|
||||||
|
|
||||||
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
|
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
|
||||||
@@ -11,10 +11,10 @@
|
|||||||
"seed:dev": "ts-node src/seed.ts",
|
"seed:dev": "ts-node src/seed.ts",
|
||||||
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
||||||
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
|
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
|
||||||
"start:test": "node -e \"process.env.NODE_ENV='test'; require('./dist/main.js')\"",
|
"start:staging": "node -e \"process.env.NODE_ENV='staging'; require('./dist/main.js')\"",
|
||||||
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
|
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
|
||||||
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
|
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
|
||||||
"pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test",
|
"pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
|
||||||
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
|
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
|
||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||||
|
|
||||||
describe('resolveDakaoNatsNames', () => {
|
describe('resolveDakaoNatsNames', () => {
|
||||||
it('resolves staging subjects and JetStream resources from NODE_ENV=test', () => {
|
it('resolves staging subjects and JetStream resources from NODE_ENV=staging', () => {
|
||||||
expect(resolveDakaoNatsNames('test')).toEqual({
|
expect(resolveDakaoNatsNames('staging')).toEqual({
|
||||||
env: 'staging',
|
env: 'staging',
|
||||||
shortEnv: 'STG',
|
shortEnv: 'STG',
|
||||||
subjects: {
|
subjects: {
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export function resolveDakaoNatsNames(
|
|||||||
|
|
||||||
function resolveRuntimeEnv(nodeEnv?: string): DakaoRuntimeEnv {
|
function resolveRuntimeEnv(nodeEnv?: string): DakaoRuntimeEnv {
|
||||||
if (nodeEnv === 'prod' || nodeEnv === 'production') return 'prod';
|
if (nodeEnv === 'prod' || nodeEnv === 'production') return 'prod';
|
||||||
if (nodeEnv === 'test' || nodeEnv === 'staging') return 'staging';
|
if (nodeEnv === 'staging') return 'staging';
|
||||||
return 'dev';
|
return 'dev';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,11 +8,18 @@ function makePublisher() {
|
|||||||
enqueueAndPublish: jest.fn().mockResolvedValue(undefined),
|
enqueueAndPublish: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as DakaoOutboxService;
|
} as unknown as DakaoOutboxService;
|
||||||
const secretService = {} as SecretService;
|
const secretService = {} as SecretService;
|
||||||
|
const previousNodeEnv = process.env.NODE_ENV;
|
||||||
|
process.env.NODE_ENV = 'staging';
|
||||||
|
|
||||||
|
try {
|
||||||
const publisher = new DakaoPublisher(secretService, outboxService, {
|
const publisher = new DakaoPublisher(secretService, outboxService, {
|
||||||
instanceId: 'test',
|
instanceId: 'staging-instance',
|
||||||
});
|
});
|
||||||
|
|
||||||
return { publisher, outboxService };
|
return { publisher, outboxService };
|
||||||
|
} finally {
|
||||||
|
process.env.NODE_ENV = previousNodeEnv;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getPublishedEnvelope(
|
function getPublishedEnvelope(
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ describe('resolveMongoDbName', () => {
|
|||||||
|
|
||||||
it('uses isolated databases for non-production environments', () => {
|
it('uses isolated databases for non-production environments', () => {
|
||||||
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
|
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
|
||||||
expect(resolveMongoDbName('test')).toBe('lolympus-test');
|
expect(resolveMongoDbName('staging')).toBe('lolympus-staging');
|
||||||
expect(resolveMongoDbName('')).toBe('lolympus-dev');
|
expect(resolveMongoDbName('')).toBe('lolympus-dev');
|
||||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
|||||||
|
|
||||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||||
if (nodeEnv === 'prod') return 'lolympus';
|
if (nodeEnv === 'prod') return 'lolympus';
|
||||||
if (nodeEnv === 'test') return 'lolympus-test';
|
if (nodeEnv === 'staging') return 'lolympus-staging';
|
||||||
return 'lolympus-dev';
|
return 'lolympus-dev';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
}
|
}
|
||||||
if (arg === '--env') {
|
if (arg === '--env') {
|
||||||
const value = argv[index + 1];
|
const value = argv[index + 1];
|
||||||
if (!value) throw new Error('--env requires dev, test, or prod.');
|
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||||
nodeEnv = value;
|
nodeEnv = value;
|
||||||
index += 1;
|
index += 1;
|
||||||
continue;
|
continue;
|
||||||
@@ -164,8 +164,8 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
throw new Error(`Unknown argument: ${arg}`);
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!['dev', 'test', 'prod'].includes(nodeEnv)) {
|
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
throw new Error('--env must be dev, test, or prod.');
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
}
|
}
|
||||||
if (communityId && !mongoose.isValidObjectId(communityId)) {
|
if (communityId && !mongoose.isValidObjectId(communityId)) {
|
||||||
throw new Error('--community-id must be a valid ObjectId.');
|
throw new Error('--community-id must be a valid ObjectId.');
|
||||||
@@ -198,7 +198,7 @@ function printHelp() {
|
|||||||
Options:
|
Options:
|
||||||
--community-id <id> Community ObjectId. Defaults to env or first community.
|
--community-id <id> Community ObjectId. Defaults to env or first community.
|
||||||
--dry-run Print the payload summary without writing.
|
--dry-run Print the payload summary without writing.
|
||||||
--env <env> dev | test | prod. Default: NODE_ENV or dev.
|
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||||
--replace Delete previous temp matches created by this script first.
|
--replace Delete previous temp matches created by this script first.
|
||||||
--scheduled-at <iso> Scheduled date. Default: yesterday.
|
--scheduled-at <iso> Scheduled date. Default: yesterday.
|
||||||
--title <title> Match title. Default: timestamped temp title.
|
--title <title> Match title. Default: timestamped temp title.
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
}
|
}
|
||||||
if (arg === '--env') {
|
if (arg === '--env') {
|
||||||
const value = argv[index + 1];
|
const value = argv[index + 1];
|
||||||
if (!value) throw new Error('--env requires dev, test, or prod.');
|
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||||
nodeEnv = value;
|
nodeEnv = value;
|
||||||
index += 1;
|
index += 1;
|
||||||
continue;
|
continue;
|
||||||
@@ -104,8 +104,8 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
throw new Error(`Unknown argument: ${arg}`);
|
throw new Error(`Unknown argument: ${arg}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!['dev', 'test', 'prod'].includes(nodeEnv)) {
|
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||||
throw new Error('--env must be dev, test, or prod.');
|
throw new Error('--env must be dev, staging, or prod.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { dryRun, limit, nodeEnv };
|
return { dryRun, limit, nodeEnv };
|
||||||
@@ -119,7 +119,7 @@ function printHelp() {
|
|||||||
Options:
|
Options:
|
||||||
--dry-run Print affected counts without writing. Default.
|
--dry-run Print affected counts without writing. Default.
|
||||||
--apply Apply updates to MongoDB.
|
--apply Apply updates to MongoDB.
|
||||||
--env <env> dev | test | prod. Default: NODE_ENV or dev.
|
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||||
--limit <n> Only scan first n documents per collection.
|
--limit <n> Only scan first n documents per collection.
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,9 @@ async function main() {
|
|||||||
await loadMachineEnvFile();
|
await loadMachineEnvFile();
|
||||||
|
|
||||||
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
||||||
logger: options.dryRun ? ['log', 'warn', 'error'] : ['log', 'warn', 'error'],
|
logger: options.dryRun
|
||||||
|
? ['log', 'warn', 'error']
|
||||||
|
: ['log', 'warn', 'error'],
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -145,14 +147,19 @@ async function main() {
|
|||||||
`[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`,
|
`[team-index migration] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${dbName}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const stats = await migrateTeamIndex(connection.db as Parameters<typeof migrateTeamIndex>[0], {
|
const stats = await migrateTeamIndex(
|
||||||
|
connection.db as Parameters<typeof migrateTeamIndex>[0],
|
||||||
|
{
|
||||||
dryRun: options.dryRun,
|
dryRun: options.dryRun,
|
||||||
limit: options.limit,
|
limit: options.limit,
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
console.table(stats);
|
console.table(stats);
|
||||||
if (options.dryRun) {
|
if (options.dryRun) {
|
||||||
console.log('No writes were made. Re-run with --apply to update documents.');
|
console.log(
|
||||||
|
'No writes were made. Re-run with --apply to update documents.',
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log('Migration applied.');
|
console.log('Migration applied.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ export class SecretService {
|
|||||||
environment:
|
environment:
|
||||||
process.env.NODE_ENV === 'prod'
|
process.env.NODE_ENV === 'prod'
|
||||||
? 'prod'
|
? 'prod'
|
||||||
: process.env.NODE_ENV === 'test'
|
: process.env.NODE_ENV === 'staging'
|
||||||
? 'staging'
|
? 'staging'
|
||||||
: 'dev',
|
: 'dev',
|
||||||
projectId: bootstrapConfig.projectId,
|
projectId: bootstrapConfig.projectId,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
VITE_API_BASE_URL=https://lolympus-test-api.dahyeon.us
|
VITE_API_BASE_URL=https://lolympus-staging-api.dahyeon.us
|
||||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||||
@@ -6,9 +6,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"build:test": "tsc -b && vite build --mode test",
|
"build:staging": "tsc -b && vite build --mode staging",
|
||||||
"build:prod": "tsc -b && vite build --mode production",
|
"build:prod": "tsc -b && vite build --mode production",
|
||||||
"deploy:test": "node ../../scripts/deploy-cloudflare-pages.mjs test",
|
"deploy:staging": "node ../../scripts/deploy-cloudflare-pages.mjs staging",
|
||||||
"deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod",
|
"deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod",
|
||||||
"pages:login": "wrangler login",
|
"pages:login": "wrangler login",
|
||||||
"pages:whoami": "wrangler whoami",
|
"pages:whoami": "wrangler whoami",
|
||||||
|
|||||||
+3
-3
@@ -5,14 +5,14 @@
|
|||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start:api:dev": "pnpm --filter api start:dev",
|
"start:api:dev": "pnpm --filter api start:dev",
|
||||||
"start:api:test": "pnpm --filter api start:test",
|
"start:api:staging": "pnpm --filter api start:staging",
|
||||||
"start:api:prod": "pnpm --filter api start:prod",
|
"start:api:prod": "pnpm --filter api start:prod",
|
||||||
"start:api": "pnpm --filter api start:prod",
|
"start:api": "pnpm --filter api start:prod",
|
||||||
"build:api": "pnpm --filter api build",
|
"build:api": "pnpm --filter api build",
|
||||||
"dev:web": "pnpm --filter web dev",
|
"dev:web": "pnpm --filter web dev",
|
||||||
"build:web:test": "pnpm --filter web build:test",
|
"build:web:staging": "pnpm --filter web build:staging",
|
||||||
"build:web:prod": "pnpm --filter web build:prod",
|
"build:web:prod": "pnpm --filter web build:prod",
|
||||||
"deploy:web:test": "node scripts/deploy-cloudflare-pages.mjs test",
|
"deploy:web:staging": "node scripts/deploy-cloudflare-pages.mjs staging",
|
||||||
"deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod",
|
"deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const { MongoClient, ObjectId } = require("mongodb");
|
|||||||
|
|
||||||
const CONFIG = {
|
const CONFIG = {
|
||||||
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
||||||
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
|
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
|
||||||
COMMUNITY_ID: new ObjectId(
|
COMMUNITY_ID: new ObjectId(
|
||||||
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
||||||
),
|
),
|
||||||
@@ -137,14 +137,18 @@ async function fetchRiotJson({ host, path, query }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 429) {
|
if (response.status === 429) {
|
||||||
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
|
const retryAfterSeconds = Number(
|
||||||
|
response.headers.get("retry-after") ?? 1,
|
||||||
|
);
|
||||||
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (response.status === 404) return null;
|
if (response.status === 404) return null;
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = await response.text().catch(() => "");
|
const body = await response.text().catch(() => "");
|
||||||
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
|
throw new Error(
|
||||||
|
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
@@ -190,13 +194,14 @@ async function fetchRecentMatchIdsByPuuid(puuid) {
|
|||||||
|
|
||||||
async function fetchRiotData({ riotId }) {
|
async function fetchRiotData({ riotId }) {
|
||||||
const fallback = splitRiotId(riotId);
|
const fallback = splitRiotId(riotId);
|
||||||
const account =
|
const account = (await fetchAccountByRiotId(fallback)) ?? {
|
||||||
(await fetchAccountByRiotId(fallback)) ?? {
|
|
||||||
...fallback,
|
...fallback,
|
||||||
puuid: normalizeString(INPUT.puuid),
|
puuid: normalizeString(INPUT.puuid),
|
||||||
};
|
};
|
||||||
if (!account?.puuid) {
|
if (!account?.puuid) {
|
||||||
throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`);
|
throw new Error(
|
||||||
|
`Riot account not found and PUUID was not provided: ${riotId}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [summoner, leagueEntries, championMasteries, matchIds] =
|
const [summoner, leagueEntries, championMasteries, matchIds] =
|
||||||
@@ -280,7 +285,9 @@ function buildRiotAccount(riotData, now) {
|
|||||||
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
|
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
|
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
|
||||||
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)),
|
tierHistory: riotData.leagueEntries.map((entry) =>
|
||||||
|
toTierHistory(entry, now),
|
||||||
|
),
|
||||||
matchIds: riotData.matchIds,
|
matchIds: riotData.matchIds,
|
||||||
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
|
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
|
||||||
championMasteries: riotData.championMasteries
|
championMasteries: riotData.championMasteries
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* Apply already-saved Dakao user bootstrap data into lolympus-test.user.
|
* Apply already-saved Dakao user bootstrap data into lolympus-staging.user.
|
||||||
*
|
*
|
||||||
* This script does NOT call Riot API.
|
* This script does NOT call Riot API.
|
||||||
*
|
*
|
||||||
* It reads saved documents from one of:
|
* It reads saved documents from one of:
|
||||||
* 1. lolympus-test.DakaoUserBootstrapRun
|
* 1. lolympus-staging.DakaoUserBootstrapRun
|
||||||
* 2. lolympus-test.DakaoUserBootstrapCandidate
|
* 2. lolympus-staging.DakaoUserBootstrapCandidate
|
||||||
*
|
*
|
||||||
* It only applies users that already have a valid Riot identity:
|
* It only applies users that already have a valid Riot identity:
|
||||||
* - dryRunUsers[].doc.riotAccounts[0].puuid, or
|
* - dryRunUsers[].doc.riotAccounts[0].puuid, or
|
||||||
@@ -34,7 +34,7 @@ const { MongoClient, ObjectId } = require("mongodb");
|
|||||||
|
|
||||||
const CONFIG = {
|
const CONFIG = {
|
||||||
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
|
||||||
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
|
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
|
||||||
COMMUNITY_ID: new ObjectId(
|
COMMUNITY_ID: new ObjectId(
|
||||||
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
|
||||||
),
|
),
|
||||||
@@ -151,14 +151,19 @@ function buildPlanFromDryRunUser(planned, now) {
|
|||||||
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
|
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
|
||||||
"planned.communityId",
|
"planned.communityId",
|
||||||
),
|
),
|
||||||
kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId),
|
kakaoTalkId: normalizeString(
|
||||||
|
planned.filter?.kakaoTalkId ?? doc.kakaoTalkId,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
doc: removeUndefined({
|
doc: removeUndefined({
|
||||||
_id:
|
_id:
|
||||||
doc._id && ObjectId.isValid(String(doc._id))
|
doc._id && ObjectId.isValid(String(doc._id))
|
||||||
? toObjectId(doc._id, "planned.doc._id")
|
? toObjectId(doc._id, "planned.doc._id")
|
||||||
: new ObjectId(),
|
: new ObjectId(),
|
||||||
communityId: toObjectId(doc.communityId ?? CONFIG.COMMUNITY_ID, "doc.communityId"),
|
communityId: toObjectId(
|
||||||
|
doc.communityId ?? CONFIG.COMMUNITY_ID,
|
||||||
|
"doc.communityId",
|
||||||
|
),
|
||||||
role: doc.role ?? "member",
|
role: doc.role ?? "member",
|
||||||
kakaoTalkId: normalizeString(doc.kakaoTalkId),
|
kakaoTalkId: normalizeString(doc.kakaoTalkId),
|
||||||
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
|
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
|
||||||
@@ -228,12 +233,18 @@ function buildPlanFromCandidate(candidate, now) {
|
|||||||
return {
|
return {
|
||||||
source: "candidate",
|
source: "candidate",
|
||||||
filter: {
|
filter: {
|
||||||
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
|
communityId: toObjectId(
|
||||||
|
candidate.communityId ?? CONFIG.COMMUNITY_ID,
|
||||||
|
"candidate.communityId",
|
||||||
|
),
|
||||||
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
||||||
},
|
},
|
||||||
doc: removeUndefined({
|
doc: removeUndefined({
|
||||||
_id: new ObjectId(),
|
_id: new ObjectId(),
|
||||||
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
|
communityId: toObjectId(
|
||||||
|
candidate.communityId ?? CONFIG.COMMUNITY_ID,
|
||||||
|
"candidate.communityId",
|
||||||
|
),
|
||||||
role: candidate.role ?? "member",
|
role: candidate.role ?? "member",
|
||||||
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
|
||||||
kakaoTalkNickname: normalizeString(
|
kakaoTalkNickname: normalizeString(
|
||||||
@@ -300,7 +311,9 @@ async function loadPlansFromCandidates(lolympusDb, now) {
|
|||||||
communityId: CONFIG.COMMUNITY_ID,
|
communityId: CONFIG.COMMUNITY_ID,
|
||||||
}).toArray();
|
}).toArray();
|
||||||
const plans = dedupePlans(
|
const plans = dedupePlans(
|
||||||
candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean),
|
candidates
|
||||||
|
.map((candidate) => buildPlanFromCandidate(candidate, now))
|
||||||
|
.filter(Boolean),
|
||||||
);
|
);
|
||||||
return { sourceRun: null, plans };
|
return { sourceRun: null, plans };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
* -> join nickname base with RiotAccount.gameName
|
* -> join nickname base with RiotAccount.gameName
|
||||||
* -> verify/fetch puuid from Riot Account API
|
* -> verify/fetch puuid from Riot Account API
|
||||||
* -> fetch summoner / league / mastery / recent match ids from Riot API
|
* -> fetch summoner / league / mastery / recent match ids from Riot API
|
||||||
* -> upsert lolympus-test.user
|
* -> upsert lolympus-staging.user
|
||||||
*/
|
*/
|
||||||
|
|
||||||
"use strict";
|
"use strict";
|
||||||
@@ -32,7 +32,7 @@ const CONFIG = {
|
|||||||
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
|
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
|
||||||
|
|
||||||
DAKAO_DB_NAME: "dakao",
|
DAKAO_DB_NAME: "dakao",
|
||||||
LOLYMPUS_DB_NAME: "lolympus-test",
|
LOLYMPUS_DB_NAME: "lolympus-staging",
|
||||||
RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao",
|
RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao",
|
||||||
RIOT_ACCOUNT_COLLECTION_NAME:
|
RIOT_ACCOUNT_COLLECTION_NAME:
|
||||||
process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount",
|
process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount",
|
||||||
@@ -50,7 +50,7 @@ const CONFIG = {
|
|||||||
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
|
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
|
||||||
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
|
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
|
||||||
|
|
||||||
// Safe default. Set DRY_RUN=false to write into lolympus-test.user.
|
// Safe default. Set DRY_RUN=false to write into lolympus-staging.user.
|
||||||
DRY_RUN: process.env.DRY_RUN !== "false",
|
DRY_RUN: process.env.DRY_RUN !== "false",
|
||||||
SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false",
|
SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false",
|
||||||
OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false",
|
OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false",
|
||||||
@@ -214,7 +214,10 @@ function remember(map, kakaoTalkId, patch) {
|
|||||||
const nickname =
|
const nickname =
|
||||||
normalizeString(patch.kakaoTalkNickname) ||
|
normalizeString(patch.kakaoTalkNickname) ||
|
||||||
normalizeString(current.kakaoTalkNickname);
|
normalizeString(current.kakaoTalkNickname);
|
||||||
const sources = new Set([...(current.sources ?? []), ...(patch.sources ?? [])]);
|
const sources = new Set([
|
||||||
|
...(current.sources ?? []),
|
||||||
|
...(patch.sources ?? []),
|
||||||
|
]);
|
||||||
const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt]
|
const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.map((value) => new Date(value));
|
.map((value) => new Date(value));
|
||||||
@@ -229,7 +232,9 @@ function remember(map, kakaoTalkId, patch) {
|
|||||||
sources: [...sources],
|
sources: [...sources],
|
||||||
lastSeenAt:
|
lastSeenAt:
|
||||||
lastSeenCandidates.length > 0
|
lastSeenCandidates.length > 0
|
||||||
? new Date(Math.max(...lastSeenCandidates.map((date) => date.getTime())))
|
? new Date(
|
||||||
|
Math.max(...lastSeenCandidates.map((date) => date.getTime())),
|
||||||
|
)
|
||||||
: null,
|
: null,
|
||||||
recentMessageCount:
|
recentMessageCount:
|
||||||
(current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0),
|
(current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0),
|
||||||
@@ -361,7 +366,12 @@ function pickRiotAccountForCandidate(candidate, index) {
|
|||||||
|
|
||||||
const nicknameBase = candidate.nicknameBase;
|
const nicknameBase = candidate.nicknameBase;
|
||||||
if (!nicknameBase) {
|
if (!nicknameBase) {
|
||||||
return { source: "no-nickname-base", account: null, override, ambiguous: [] };
|
return {
|
||||||
|
source: "no-nickname-base",
|
||||||
|
account: null,
|
||||||
|
override,
|
||||||
|
ambiguous: [],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? [];
|
const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? [];
|
||||||
@@ -422,7 +432,9 @@ async function fetchRiotJson({ host, path, query }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 429) {
|
if (response.status === 429) {
|
||||||
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
|
const retryAfterSeconds = Number(
|
||||||
|
response.headers.get("retry-after") ?? 1,
|
||||||
|
);
|
||||||
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
await sleep(Math.max(1, retryAfterSeconds) * 1000);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -431,7 +443,9 @@ async function fetchRiotJson({ host, path, query }) {
|
|||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = await response.text().catch(() => "");
|
const body = await response.text().catch(() => "");
|
||||||
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
|
throw new Error(
|
||||||
|
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json();
|
return response.json();
|
||||||
@@ -670,11 +684,14 @@ async function enrichCandidatesWithRiot({ candidates, riotAccountIndex }) {
|
|||||||
riotApiError,
|
riotApiError,
|
||||||
riotEnrichment,
|
riotEnrichment,
|
||||||
riotEnrichmentError,
|
riotEnrichmentError,
|
||||||
preferredPositions: normalizePositions(match.override?.preferredPositions),
|
preferredPositions: normalizePositions(
|
||||||
|
match.override?.preferredPositions,
|
||||||
|
),
|
||||||
role: match.override?.role ?? "member",
|
role: match.override?.role ?? "member",
|
||||||
isActivated: match.override?.isActivated ?? true,
|
isActivated: match.override?.isActivated ?? true,
|
||||||
targetKakaoTalkNickname:
|
targetKakaoTalkNickname:
|
||||||
normalizeString(match.override?.nickname) || candidate.kakaoTalkNickname,
|
normalizeString(match.override?.nickname) ||
|
||||||
|
candidate.kakaoTalkNickname,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -798,7 +815,7 @@ async function upsertUsers({ lolympusDb, candidates }) {
|
|||||||
preferredPositions:
|
preferredPositions:
|
||||||
candidate.preferredPositions?.length > 0
|
candidate.preferredPositions?.length > 0
|
||||||
? candidate.preferredPositions
|
? candidate.preferredPositions
|
||||||
: existing?.preferredPositions ?? [],
|
: (existing?.preferredPositions ?? []),
|
||||||
isActivated: candidate.isActivated ?? true,
|
isActivated: candidate.isActivated ?? true,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,49 +1,51 @@
|
|||||||
import { spawnSync } from 'node:child_process';
|
import { spawnSync } from "node:child_process";
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
import { dirname, resolve } from 'node:path';
|
import { dirname, resolve } from "node:path";
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const repoRoot = resolve(__dirname, '..');
|
const repoRoot = resolve(__dirname, "..");
|
||||||
const webDir = resolve(repoRoot, 'apps/web');
|
const webDir = resolve(repoRoot, "apps/web");
|
||||||
|
|
||||||
const target = process.argv[2];
|
const target = process.argv[2];
|
||||||
if (target !== 'test' && target !== 'prod') {
|
if (target !== "staging" && target !== "prod") {
|
||||||
console.error('Usage: node scripts/deploy-cloudflare-pages.mjs <test|prod>');
|
console.error(
|
||||||
|
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const viteMode = target === 'prod' ? 'production' : 'test';
|
const viteMode = target === "prod" ? "production" : "staging";
|
||||||
const projectName =
|
const projectName =
|
||||||
process.env.CF_PAGES_PROJECT_NAME ??
|
process.env.CF_PAGES_PROJECT_NAME ??
|
||||||
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ??
|
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ??
|
||||||
'lolympus';
|
"lolympus";
|
||||||
const testBranch = process.env.CF_PAGES_TEST_BRANCH ?? 'test';
|
const stagingBranch = process.env.CF_PAGES_STAGING_BRANCH ?? "staging";
|
||||||
|
|
||||||
validateEnv(viteMode);
|
validateEnv(viteMode);
|
||||||
run('pnpm', ['--filter', 'web', 'run', `build:${target}`], repoRoot);
|
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
|
||||||
|
|
||||||
const deployArgs = [
|
const deployArgs = [
|
||||||
'exec',
|
"exec",
|
||||||
'wrangler',
|
"wrangler",
|
||||||
'pages',
|
"pages",
|
||||||
'deploy',
|
"deploy",
|
||||||
'dist',
|
"dist",
|
||||||
'--project-name',
|
"--project-name",
|
||||||
projectName,
|
projectName,
|
||||||
];
|
];
|
||||||
|
|
||||||
if (target === 'test') {
|
if (target === "staging") {
|
||||||
deployArgs.push('--branch', testBranch);
|
deployArgs.push("--branch", stagingBranch);
|
||||||
}
|
}
|
||||||
|
|
||||||
run('pnpm', deployArgs, webDir);
|
run("pnpm", deployArgs, webDir);
|
||||||
|
|
||||||
function run(command, args, cwd) {
|
function run(command, args, cwd) {
|
||||||
const result = spawnSync(command, args, {
|
const result = spawnSync(command, args, {
|
||||||
cwd,
|
cwd,
|
||||||
stdio: 'inherit',
|
stdio: "inherit",
|
||||||
shell: process.platform === 'win32',
|
shell: process.platform === "win32",
|
||||||
});
|
});
|
||||||
if (result.status !== 0) {
|
if (result.status !== 0) {
|
||||||
process.exit(result.status ?? 1);
|
process.exit(result.status ?? 1);
|
||||||
@@ -52,8 +54,8 @@ function run(command, args, cwd) {
|
|||||||
|
|
||||||
function validateEnv(mode) {
|
function validateEnv(mode) {
|
||||||
const fileEnv = [
|
const fileEnv = [
|
||||||
'.env',
|
".env",
|
||||||
'.env.local',
|
".env.local",
|
||||||
`.env.${mode}`,
|
`.env.${mode}`,
|
||||||
`.env.${mode}.local`,
|
`.env.${mode}.local`,
|
||||||
].reduce((acc, fileName) => {
|
].reduce((acc, fileName) => {
|
||||||
@@ -62,39 +64,39 @@ function validateEnv(mode) {
|
|||||||
return { ...acc, ...parseEnvFile(envFile) };
|
return { ...acc, ...parseEnvFile(envFile) };
|
||||||
}, {});
|
}, {});
|
||||||
const requiredKeys = [
|
const requiredKeys = [
|
||||||
'VITE_API_BASE_URL',
|
"VITE_API_BASE_URL",
|
||||||
'VITE_DEFAULT_COMMUNITY_ID',
|
"VITE_DEFAULT_COMMUNITY_ID",
|
||||||
'VITE_MSAL_CLIENT_ID',
|
"VITE_MSAL_CLIENT_ID",
|
||||||
'VITE_MSAL_AUTHORITY',
|
"VITE_MSAL_AUTHORITY",
|
||||||
'VITE_MSAL_API_SCOPE',
|
"VITE_MSAL_API_SCOPE",
|
||||||
'VITE_MSAL_REDIRECT_URI',
|
"VITE_MSAL_REDIRECT_URI",
|
||||||
];
|
];
|
||||||
const missing = requiredKeys.filter((key) => {
|
const missing = requiredKeys.filter((key) => {
|
||||||
const value = process.env[key] ?? fileEnv[key];
|
const value = process.env[key] ?? fileEnv[key];
|
||||||
return !value || value.includes('<');
|
return !value || value.includes("<");
|
||||||
});
|
});
|
||||||
|
|
||||||
if (missing.length === 0) return;
|
if (missing.length === 0) return;
|
||||||
|
|
||||||
console.error(
|
console.error(
|
||||||
[
|
[
|
||||||
`Missing Cloudflare Pages ${mode} build env: ${missing.join(', ')}`,
|
`Missing Cloudflare Pages ${mode} build env: ${missing.join(", ")}`,
|
||||||
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
|
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
|
||||||
`Use apps/web/.env.${mode}.example as a template.`,
|
`Use apps/web/.env.${mode}.example as a template.`,
|
||||||
].join('\n'),
|
].join("\n"),
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseEnvFile(path) {
|
function parseEnvFile(path) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
readFileSync(path, 'utf8')
|
readFileSync(path, "utf8")
|
||||||
.split(/\r?\n/)
|
.split(/\r?\n/)
|
||||||
.map((line) => line.trim())
|
.map((line) => line.trim())
|
||||||
.filter((line) => line && !line.startsWith('#'))
|
.filter((line) => line && !line.startsWith("#"))
|
||||||
.map((line) => {
|
.map((line) => {
|
||||||
const separatorIndex = line.indexOf('=');
|
const separatorIndex = line.indexOf("=");
|
||||||
if (separatorIndex === -1) return [line, ''];
|
if (separatorIndex === -1) return [line, ""];
|
||||||
const key = line.slice(0, separatorIndex).trim();
|
const key = line.slice(0, separatorIndex).trim();
|
||||||
let value = line.slice(separatorIndex + 1).trim();
|
let value = line.slice(separatorIndex + 1).trim();
|
||||||
if (
|
if (
|
||||||
|
|||||||
Reference in new issue
Block a user