Commit 636faf65 authored by nanahira's avatar nanahira

first

parents
Pipeline #24768 failed with stages
in 1 minute and 32 seconds
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
\ No newline at end of file
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
.build-image:
stage: build
script:
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-x86:
extends: .build-image
tags:
- docker
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
.deploy:
stage: deploy
tags:
- docker
script:
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
- docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG $TARGET_IMAGE
- docker push $TARGET_IMAGE
deploy_latest:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:latest
only:
- master
deploy_branch:
extends: .deploy
variables:
TARGET_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:lts-bookworm-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/log/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
COPY ./config.example.yaml ./config.yaml
EXPOSE 3000
CMD [ "npm", "run", "start:prod" ]
This diff is collapsed.
# App name
App description.
## Installation
```bash
$ npm install
```
## Config
Make a copy of `config.example.yaml` to `config.yaml`.
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## License
AGPLv3
host: '::'
port: 3000
DB_HOST: 'localhost'
DB_PORT: 3306
DB_USER: 'root'
DB_PASS: 'root'
DB_NAME: 'test'
DEALER_USERNAME: '发牌姬'
\ No newline at end of file
#!/bin/bash
npm install --save typeorm @nestjs/typeorm pg pg-native nicot
#!/bin/bash
npm install --save \
class-validator \
class-transformer \
@nestjs/swagger \
@nestjs/config \
yaml
npm install --save-dev \
@types/express
npm i --save-exact --save-dev eslint@8.22.0
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
}
This diff is collapsed.
{
"name": "dealer-counter",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.1.17",
"@nestjs/typeorm": "^10.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"mysql": "^2.18.1",
"nicot": "^1.0.53",
"pg": "^8.11.3",
"pg-native": "^3.0.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"typeorm": "^0.3.17",
"yaml": "^2.3.4"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "8.22.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should be defined', () => {
expect(appController).toBeDefined();
});
});
});
import { Controller, Get, Param } from '@nestjs/common';
import { AppService } from './app.service';
import { ApiOkResponse, ApiOperation, ApiParam } from '@nestjs/swagger';
import { ReturnMessageDto } from 'nicot';
import { MatchResultDto } from './dto/match-result.dto';
class MatchResultReturnMessageDto extends ReturnMessageDto(MatchResultDto) {}
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('dealer')
@ApiOperation({
summary: '发牌姬的对局统计',
})
@ApiOkResponse({
type: MatchResultReturnMessageDto,
})
async getDealerMatchResult() {
return await this.appService.getDealerMatchResult();
}
@Get('user/:username')
@ApiOperation({
summary: '用户的对局统计',
})
@ApiParam({
name: 'username',
description: '用户名',
})
@ApiOkResponse({
type: MatchResultReturnMessageDto,
})
async getUserMatchResult(@Param('username') username: string) {
return await this.appService.getUserMatchResult(username);
}
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { loadConfig } from './utility/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DuelLogPlayer } from './entities/DuelLogPlayer';
import { DuelLog } from './entities/DuelLog';
@Module({
imports: [
ConfigModule.forRoot({
load: [loadConfig],
isGlobal: true,
ignoreEnvVars: true,
ignoreEnvFile: true,
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
type: 'mysql',
entities: [],
autoLoadEntities: true,
synchronize: false,
host: config.get('DB_HOST'),
port: parseInt(config.get('DB_PORT')) || 3306,
username: config.get('DB_USER'),
password: config.get('DB_PASS'),
database: config.get('DB_NAME'),
supportBigNumbers: true,
bigNumberStrings: false,
}),
}),
TypeOrmModule.forFeature([DuelLogPlayer, DuelLog]),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Injectable, ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { DuelLogPlayer } from './entities/DuelLogPlayer';
import { FindOptionsWhere, Not, Repository } from 'typeorm';
import { MatchResultDto } from './dto/match-result.dto';
import { GenericReturnMessageDto } from 'nicot';
@Injectable()
export class AppService extends ConsoleLogger {
private dealerUsername = this.config.get<string>('DEALER_USERNAME');
constructor(
private readonly config: ConfigService,
@InjectRepository(DuelLogPlayer)
private readonly duelLogPlayerRepository: Repository<DuelLogPlayer>,
) {
super('app');
}
async getMatchResult(where: FindOptionsWhere<DuelLogPlayer>) {
const [win, total] = await Promise.all([
this.duelLogPlayerRepository.count({
where: {
...where,
winner: 1,
},
}),
this.duelLogPlayerRepository.count({
where,
}),
]);
const dto = new MatchResultDto();
dto.win = win || 0;
dto.total = total || 0;
dto.lose = dto.total - dto.win;
return new GenericReturnMessageDto(200, 'success', dto);
}
async getDealerMatchResult() {
return await this.getMatchResult({
realName: this.dealerUsername,
});
}
async getUserMatchResult(username: string) {
return await this.getMatchResult({
realName: username,
});
}
}
// Blank for nicot use.
export class MatchResultDto {
win: number;
lose: number;
total: number;
}
import {Column, PrimaryGeneratedColumn} from "typeorm";
import {CreateAndUpdateTimeBase} from "./CreateAndUpdateTimeBase";
export abstract class BasePlayer extends CreateAndUpdateTimeBase {
@PrimaryGeneratedColumn({unsigned: true, type: (global as any).PrimaryKeyType as ('bigint' | 'integer') || 'bigint'})
id: number;
@Column({ type: "varchar", length: 20 })
name: string;
@Column({ type: "tinyint" })
pos: number;
}
import { CreateDateColumn, UpdateDateColumn } from 'typeorm';
export abstract class CreateAndUpdateTimeBase {
@CreateDateColumn()
createTime: Date;
@UpdateDateColumn()
updateTime: Date;
}
import {
Column,
Entity,
Index,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import { DuelLogPlayer } from './DuelLogPlayer';
import { CreateAndUpdateTimeBase } from './CreateAndUpdateTimeBase';
@Entity({
orderBy: {
id: 'DESC',
},
})
export class DuelLog extends CreateAndUpdateTimeBase {
@PrimaryGeneratedColumn({
unsigned: true,
type: 'bigint',
})
id: number;
@Index()
@Column('datetime')
time: Date;
@Index()
@Column({ type: 'varchar', length: 20 })
name: string;
@Column('int')
roomId: number;
@Column('bigint')
cloudReplayId: number; // not very needed to become a relation
@Column({ type: 'varchar', length: 256 })
replayFileName: string;
@Column('tinyint', { unsigned: true })
roomMode: number;
@Index()
@Column('tinyint', { unsigned: true })
duelCount: number;
@OneToMany(() => DuelLogPlayer, (player) => player.duelLog)
players: DuelLogPlayer[];
}
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { BasePlayer } from './BasePlayer';
import { DuelLog } from './DuelLog';
@Entity()
export class DuelLogPlayer extends BasePlayer {
@Index()
@Column({ type: 'varchar', length: 20 })
realName: string;
@Column({ type: 'varchar', length: 64, nullable: true })
ip: string;
@Column('tinyint', { unsigned: true })
isFirst: number;
@Index()
@Column('tinyint')
score: number;
@Column('int', { nullable: true })
lp: number;
@Column('smallint', { nullable: true })
cardCount: number;
@Column('text', { nullable: true })
startDeckBuffer: string;
@Column('text', { nullable: true })
currentDeckBuffer: string;
@Column('tinyint')
winner: number;
@ManyToOne(() => DuelLog, (duelLog) => duelLog.players)
duelLog: DuelLog;
}
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
app.enableCors();
app.set('trust proxy', ['172.16.0.0/12', 'loopback']);
const config = app.get(ConfigService);
if (!config.get('NO_OPENAPI')) {
const documentConfig = new DocumentBuilder()
.setTitle('app')
.setDescription('The app')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, documentConfig);
SwaggerModule.setup('docs', app, document);
}
await app.listen(
config.get<number>('port') || 3000,
config.get<string>('host') || '::',
);
}
bootstrap();
import yaml from 'yaml';
import * as fs from 'fs';
const defaultConfig = {
host: '::',
port: 3000,
};
export type Config = typeof defaultConfig;
export async function loadConfig(): Promise<Config> {
let readConfig: Partial<Config> = {};
try {
const configText = await fs.promises.readFile('./config.yaml', 'utf-8');
readConfig = yaml.parse(configText);
} catch (e) {
console.error(`Failed to read config: ${e.toString()}`);
}
return {
...defaultConfig,
...readConfig,
...process.env,
};
}
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
/* it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
}); */
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"esModuleInterop": true
},
"compileOnSave": true,
"allowJs": true
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment