Skip to content

Commit

Permalink
rank객체 date 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
jinseok1006 committed Jun 9, 2023
1 parent e6899be commit 2161829
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
16 changes: 11 additions & 5 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express from 'express';
import type { Request, Response } from 'express';
import helmet from 'helmet';

import { contains } from './util';
import { contains, dateToString } from './util';
import {
DIFFICULTY,
binarySearchInsert,
Expand Down Expand Up @@ -39,10 +39,12 @@ app.get('/register/:diff', (req: Request, res: Response) => {
if (!req.query || !req.query.name || !req.query.sec)
return void res.send(false);

const now = new Date();
const date = dateToString(now);
const name = req.query.name as string;
const sec = parseFloat(req.query.sec as string);

const rank = { name, sec };
const rank = { date, name, sec };

binarySearchInsert(store[diff], rank);

Expand Down Expand Up @@ -72,9 +74,13 @@ app.get('/delete/:diff', (req: Request, res: Response) => {
res.send(true);
});

app.get('/save', (req: Request, res: Response) => {
writeStoreToFile(store);
res.send(true);
app.get('/save', async (req: Request, res: Response) => {
try {
await writeStoreToFile(store);
res.send(true);
} catch (err) {
res.send(false);
}
});

// 1시간 마다 파일에 저장
Expand Down
13 changes: 12 additions & 1 deletion src/store.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { readFileSync } from 'fs';
import { readFileSync, existsSync } from 'fs';
import { writeFile } from 'fs/promises';

export const DIFFICULTY = ['easy', 'normal', 'hard'] as const;
const FILE_PATH = './ranks.json';

// TODO: add Date
export interface Rank {
date: string;
name: string;
sec: number;
}
Expand All @@ -15,7 +16,16 @@ export interface Store {
hard: Rank[];
}

const getDefaultStore = (): Store => ({
easy: [],
normal: [],
hard: [],
});

export function readStoreFromFile(): Store {
// 없으면 객체를 새로 생성
if (!existsSync(FILE_PATH)) return getDefaultStore();

// 프로그램 시작시에는 동기로 읽고 서버 열기
const payload = readFileSync(FILE_PATH, 'utf-8');
const store = JSON.parse(payload) as Store;
Expand Down Expand Up @@ -49,5 +59,6 @@ export function binarySearchInsert(arr: Rank[], data: Rank) {
}
}

// 탐색이 끝난 자리에 삽입
arr.splice(low, 0, data);
}
16 changes: 16 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,19 @@ export function contains<T extends string>(
): value is T {
return list.some((item) => item === value);
}

export const dateToString = (date: Date) => {
return (
date.getFullYear() +
'-' +
date.getMonth() +
'-' +
date.getDate() +
' ' +
date.getHours() +
':' +
date.getMinutes() +
':' +
date.getSeconds()
);
};

0 comments on commit 2161829

Please sign in to comment.