Commit 11290e84 authored by nanahira's avatar nanahira

first

parents
# 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',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
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
stages:
- build
- combine
- deploy
variables:
GIT_DEPTH: "1"
CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
CONTAINER_TEST_ARM_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
CONTAINER_TEST_X86_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
build-x86:
stage: build
tags:
- docker
script:
- docker build --pull -t $CONTAINER_TEST_X86_IMAGE .
- docker push $CONTAINER_TEST_X86_IMAGE
build-arm:
stage: build
tags:
- docker-arm
script:
- docker build --pull -t $CONTAINER_TEST_ARM_IMAGE .
- docker push $CONTAINER_TEST_ARM_IMAGE
combine:
stage: combine
tags:
- docker
script:
- docker pull $CONTAINER_TEST_X86_IMAGE
- docker pull $CONTAINER_TEST_ARM_IMAGE
- docker manifest create $CONTAINER_TEST_IMAGE --amend $CONTAINER_TEST_X86_IMAGE --amend $CONTAINER_TEST_ARM_IMAGE
- docker manifest push $CONTAINER_TEST_IMAGE
deploy_latest:
stage: deploy
tags:
- docker
script:
- docker pull $CONTAINER_TEST_IMAGE
- docker tag $CONTAINER_TEST_IMAGE $CONTAINER_RELEASE_IMAGE
- docker push $CONTAINER_RELEASE_IMAGE
only:
- master
deploy_tag:
stage: deploy
tags:
- docker
variables:
CONTAINER_TAG_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
script:
- docker pull $CONTAINER_TEST_IMAGE
- docker tag $CONTAINER_TEST_IMAGE $CONTAINER_TAG_IMAGE
- docker push $CONTAINER_TAG_IMAGE
only:
- tags
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:buster-slim
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
WORKDIR /usr/src/app
COPY ./package*.json ./
RUN npm ci
COPY . ./
RUN npm run build
CMD ["npm", "run", "start:prod"]
This diff is collapsed.
#YuzuDice
## Description
下一代的骰娘。
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## License
AGPLv3
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 return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
}); */
});
});
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppLogger } from './app.logger';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeormConfig } from './config';
import { BotService } from './bot/bot.service';
import { BotLogger } from './bot/bot.logger';
import { BotController } from './bot/bot.controller';
@Module({
imports: [TypeOrmModule.forRoot(typeormConfig())],
controllers: [AppController, BotController],
providers: [AppService, AppLogger, BotService, BotLogger],
})
export class AppModule {}
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}
This diff is collapsed.
{
"name": "yuzudice",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"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": "^7.5.1",
"@nestjs/core": "^7.5.1",
"@nestjs/platform-express": "^7.5.1",
"@nestjs/typeorm": "^7.1.5",
"koishi": "^3.10.1",
"koishi-adapter-onebot": "^3.0.8",
"koishi-plugin-common": "^4.2.4",
"lodash": "^4.17.21",
"mustache": "^4.2.0",
"mysql": "^2.18.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"typeorm": "^0.2.32"
},
"devDependencies": {
"@nestjs/cli": "^7.5.1",
"@nestjs/schematics": "^7.1.3",
"@nestjs/testing": "^7.5.1",
"@types/express": "^4.17.8",
"@types/jest": "^26.0.15",
"@types/lodash": "^4.14.168",
"@types/mustache": "^4.1.1",
"@types/node": "^14.14.6",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.6.1",
"@typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
"prettier": "^2.1.2",
"supertest": "^6.0.0",
"ts-jest": "^26.4.3",
"ts-loader": "^8.0.8",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.0.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
const reasonString = `{{#reason}}因为 {{reason}} {{/reason}}`;
export const DefaultRollText =
'{{name}} {{#reason}}因为 {{reason}} {{/reason}}而投掷了 {{count}} 个 {{size}} 面骰子,投掷出了 {{result}} 点。\n{{formula}}={{result}}';
export const TooMuchCountText =
'{{name}} {{#reason}}因为 {{reason}} {{/reason}}而投掷了 {{count}} 个 {{size}} 面骰子。\n骰子滚落了一地,找不到了。';
export const TooMuchSizeText =
'{{name}} {{#reason}}因为 {{reason}} {{/reason}}而投掷了 {{count}} 个 {{size}} 面骰子。\n丢了个球。丢个球啊!';
export const defaultTemplateMap = new Map<string, string>();
defaultTemplateMap.set('roll', DefaultRollText);
defaultTemplateMap.set('too_much_count', TooMuchCountText);
defaultTemplateMap.set('too_much_size', TooMuchSizeText);
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 return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
}); */
});
});
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
import { Injectable, Scope, Logger } from '@nestjs/common';
@Injectable()
export class AppLogger extends Logger {}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppLogger } from './app.logger';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeormConfig } from './config';
@Module({
imports: [TypeOrmModule.forRoot(typeormConfig())],
controllers: [AppController],
providers: [AppService, AppLogger],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { AppLogger } from './app.logger';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';
@Injectable()
export class AppService {
constructor(
@InjectConnection('app')
private db: Connection,
private log: AppLogger,
) {
this.log.setContext('app');
}
getHello(): string {
return 'Hello World!';
}
}
import { Test, TestingModule } from '@nestjs/testing';
import { BotController } from './bot.controller';
describe('BotController', () => {
let controller: BotController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [BotController],
}).compile();
controller = module.get<BotController>(BotController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
import { Controller } from '@nestjs/common';
import { AppService } from '../app.service';
import { BotService } from './bot.service';
import { App } from 'koishi';
import * as koishiCommonPlugin from 'koishi-plugin-common';
import * as adapter from 'koishi-adapter-onebot';
const __ = typeof adapter; // just for import
@Controller('_bot')
export class BotController {
bot: App;
constructor(
private readonly appService: AppService,
private readonly botService: BotService,
) {
this.initializeBot();
}
async initializeBot() {
this.bot = new App({
type: 'onebot:ws',
selfId: process.env.CQ_ID,
server: process.env.CQ_SERVER,
token: process.env.CQ_TOKEN,
prefix: process.env.CQ_PREFIX || '.',
});
this.bot.plugin(koishiCommonPlugin);
this.loadBotRouters();
await this.bot.start();
this.botService.log.log(`Bot started.`);
}
loadBotRouters() {
// all middlewares should be here.
}
}
import { Injectable, Logger } from '@nestjs/common';
@Injectable()
export class BotLogger extends Logger {}
import { Test, TestingModule } from '@nestjs/testing';
import { BotService } from './bot.service';
describe('BotService', () => {
let service: BotService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [BotService],
}).compile();
service = module.get<BotService>(BotService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { BotLogger } from './bot.logger';
import { User } from '../entities/User';
import { Group } from '../entities/Group';
@Injectable()
export class BotService {
constructor(
@InjectConnection('app')
private db: Connection,
public log: BotLogger,
) {
this.log.setContext('bot');
}
async findOrCreateUser(id: string, name?: string) {
const repo = this.db.getRepository(User);
let ent = await repo.findOne({ where: { id } });
if (ent) {
return ent;
}
ent = new User();
ent.id = id;
ent.name = name;
try {
ent = await repo.save(ent);
} catch (e) {
this.log.error(`Failed to save user ${id}: ${e.toString()}`);
return null;
}
return ent;
}
async findOrCreateGroup(id: string) {
const repo = this.db.getRepository(Group);
let ent = await repo.findOne({ where: { id } });
if (ent) {
return ent;
}
ent = new Group();
ent.id = id;
try {
ent = await repo.save(ent);
} catch (e) {
this.log.error(`Failed to save group ${id}: ${e.toString()}`);
return null;
}
return ent;
}
}
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from './entities/User';
export function dbConfig() {
return {
host: process.env.DB_HOST,
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 3306,
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
};
}
export function typeormConfig(): TypeOrmModuleOptions {
return {
name: 'app',
type: 'mysql',
entities: [User], // entities here
synchronize: true,
...dbConfig(),
};
}
import { Column, Entity, ManyToOne, PrimaryColumn } from 'typeorm';
import { TextTemplate } from './TextTemplate';
import { Group } from './Group';
@Entity()
export class GroupTemplate extends TextTemplate {
@PrimaryColumn('varchar', { length: 32 })
key: string;
}
import { QQIDBase } from './QQIDBase';
import { Entity, OneToMany } from 'typeorm';
import { GroupTemplate } from './GroupTemplate';
@Entity()
export class Group extends QQIDBase {
@OneToMany((type) => GroupTemplate, (template) => template.group)
templates: GroupTemplate[];
renderText(key: string, data: any) {
const template = this.templates.find((t) => key === t.key);
if (this.templates) {
return template.render(data);
}
return null;
}
}
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { TextTemplate } from './TextTemplate';
import { Group } from './Group';
@Entity()
export class GroupTemplate extends TextTemplate {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('varchar', { length: 32 })
key: string;
@ManyToOne((type) => Group, (group) => group.templates)
group: Group;
}
import { TimeBase } from './TimeBase';
import { Column, Index, PrimaryColumn } from 'typeorm';
export class QQIDBase extends TimeBase {
@PrimaryColumn('varchar', { length: 12 })
id: string;
}
import { TimeBase } from './TimeBase';
import { Column, PrimaryGeneratedColumn } from 'typeorm';
import {
DefaultRollText,
TooMuchCountText,
TooMuchSizeText,
} from '../DefaultTemplate';
import * as Mustache from 'mustache';
import _ from 'lodash';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Mustache.escape = (text) => {
return text;
};
export class TextTemplate extends TimeBase {
key: string; // column differs
@Column('text')
content: string;
render(data: any) {
return Mustache.render(this.content, data);
}
}
import { CreateDateColumn, UpdateDateColumn } from 'typeorm';
export class TimeBase {
@CreateDateColumn({ select: false })
createTime: Date;
@UpdateDateColumn({ select: false })
updateTime: Date;
toObject() {
return JSON.parse(JSON.stringify(this));
}
}
import { QQIDBase } from './QQIDBase';
import { Column, Entity, Index } from 'typeorm';
@Entity()
export class User extends QQIDBase {
@Index()
@Column('varchar', { length: 32, nullable: true })
name: string;
}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
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": "es2017",
"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