This commit is contained in:
Administrator 2021-05-11 17:43:02 +08:00
parent b6728c11e4
commit 2ffebb8f48
79 changed files with 11011 additions and 0 deletions

24
.eslintrc.js Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
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',
},
};

34
.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# 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

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

10
nest-cli.json Normal file
View File

@ -0,0 +1,10 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{ "include": "**/*.yml","watchAssets": true }
],
"plugins": ["@nestjs/swagger/plugin"]
}
}

8759
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

85
package.json Normal file
View File

@ -0,0 +1,85 @@
{
"name": "chicken-game",
"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.6.15",
"@nestjs/config": "^0.6.3",
"@nestjs/core": "^7.6.15",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^7.6.15",
"@nestjs/swagger": "^4.8.0",
"@nestjs/typeorm": "^7.1.5",
"@nestx-log4js/core": "^1.5.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"js-yaml": "^4.1.0",
"mysql": "^2.18.1",
"nestjs-redis": "^1.3.3",
"node-fetch": "^2.6.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.7",
"swagger-ui-express": "^4.1.6",
"typeorm": "^0.2.32"
},
"devDependencies": {
"@nestjs/cli": "^7.6.0",
"@nestjs/schematics": "^7.3.0",
"@nestjs/testing": "^7.6.15",
"@types/express": "^4.17.11",
"@types/jest": "^26.0.22",
"@types/js-yaml": "^4.0.1",
"@types/node": "^14.14.36",
"@types/node-fetch": "^2.5.10",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"eslint": "^7.22.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^26.5.4",
"ts-loader": "^8.0.18",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.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"
}
}

18
src/admin/admin.module.ts Normal file
View File

@ -0,0 +1,18 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GoodsEntity } from 'src/goods/entities/good.entity';
import { GoodsModule } from 'src/goods/goods.module';
import { GoodsService } from 'src/goods/goods.service';
import { UserModule } from 'src/user/user.module';
import { GoodsController } from './admin_goods.controller';
@Module({
imports: [
TypeOrmModule.forFeature([GoodsEntity]),
GoodsModule,
UserModule,
],
controllers: [GoodsController],
providers:[GoodsService]
})
export class AdminModule { }

View File

@ -0,0 +1,92 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, UsePipes, Query } from '@nestjs/common';
import { GoodsService } from '../goods/goods.service';
import { UpdateGoodDto } from '../goods/dto/update-good.dto';
import { ApiOperation, ApiTags, } from '@nestjs/swagger';
import { CreateGoodDto } from 'src/goods/dto/create-good.dto';
import { HttpValidationPipe } from 'src/common/utils/HttpValidationPipe';
import { GoodsListModel } from 'src/goods/goods.model';
import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator';
@ApiTags('商品管理接口')
@Controller('admin/goods')
export class GoodsController {
constructor(
private readonly goodsService: GoodsService
) { }
//商品添加
@ApiOperation({ summary: '商品添加' })
@UsePipes(new HttpValidationPipe())
@Post()
async create(@Body() createGoodDto: CreateGoodDto) {
return await this.goodsService.create(createGoodDto);
}
//商品列表
@ApiOperation({ summary: '商品列表' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'pageIndex',
required: true,
description: '当前页',
type: Number,
})
@ApiImplicitQuery({
name: 'pageSize',
required: true,
description: '分页',
type: Number,
})
@ApiImplicitQuery({
name: 'keywords',
required: false,
description: '关键词',
type: String,
})
@Get()
async goodsList(@Query() query: GoodsListModel) {
return await this.goodsService.goodsList(query);
}
//商品详情
@ApiOperation({ summary: '商品详情' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'id',
required: true,
description: '商品ID',
type: Number,
})
@Get(':id')
async findOne(@Query('id') id: number) {
return await this.goodsService.findOne(Number(id));
}
//商品修改
@ApiOperation({ summary: '商品修改' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'id',
required: true,
description: '商品ID',
type: Number,
})
@Patch(':id')
async update(@Query('id') id: string, @Body() updateGoodDto: UpdateGoodDto) {
return await this.goodsService.updateGoods(+id, updateGoodDto);
}
//商品删除
@ApiOperation({ summary: '商品删除' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'id',
required: true,
description: '商品ID',
type: Number,
})
@Delete(':id')
async remove(@Query('id') id: string) {
return await this.goodsService.remove(+id);
}
}

View File

@ -0,0 +1,22 @@
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!');
});
});
});

12
src/app.controller.ts Normal file
View File

@ -0,0 +1,12 @@
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();
// }
}

88
src/app.module.ts Normal file
View File

@ -0,0 +1,88 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './config/configuration';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { GoodsModule } from './goods/goods.module';
import { OrderlogModule } from './orderlog/orderlog.module';
import { InvitedstatisticsModule } from './invitedstatistics/invitedstatistics.module';
import { ChickensModule } from './chickens/chickens.module';
import { ConfigurationModule } from './configuration/configuration.module';
import { AdminModule } from './admin/admin.module';
import logger from './common/utils/logger';
import { Log4jsModule } from '@nestx-log4js/core';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
ignoreEnvFile: true,
load: [configuration],
}),
Log4jsModule.forRootAsync({
inject: [ConfigService],
imports: [ConfigModule],
useFactory: (config: ConfigService) => {
return {
config: logger,
};
},
}),
// RedisModule.forRootAsync({
// imports: [ConfigModule],
// useFactory: (configService: ConfigService) => {
// const nodes = configService.get('redis.cluster.nodes');
// if (nodes) {
// console.log('redis集群模式');
// return {
// nodes: nodes,
// };
// } else {
// console.log('redis普通模式');
// return {
// host: configService.get('redis.host'),
// port: configService.get('redis.port'),
// password: configService.get('redis.password', undefined),
// };
// }
// }, // or use async method
// inject: [ConfigService],
// }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (
configService: ConfigService,
) => ({
name: 'default',
type: 'mysql',
host: configService.get('database.host'),
port: configService.get('database.port'),
username: configService.get('database.username'),
password: configService.get('database.password'),
database: configService.get('database.dbname'),
synchronize: configService.get<boolean>('database.synchronize'),
logging: configService.get('database.logging'),
dropSchema: configService.get('database.drop_schema'),
charset: configService.get<string>('database.charset'),
entityPrefix: 'ck_',
entities: ['dist/**/*.entity{.ts,.js}'],
migrations: ['dist/**/*.migration{.ts,.js}'],
subscribers: ['dist/**/*.subscriber{.ts,.js}'],
}),
}),
AdminModule,
UserModule,
GoodsModule,
OrderlogModule,
InvitedstatisticsModule,
ChickensModule,
ConfigurationModule,
],
controllers: [AppController],
providers: [AppService, ConfigService],
})
export class AppModule { }

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChickensController } from './chickens.controller';
import { ChickensService } from './chickens.service';
describe('ChickensController', () => {
let controller: ChickensController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ChickensController],
providers: [ChickensService],
}).compile();
controller = module.get<ChickensController>(ChickensController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,54 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CustomResult, SuccessResult } from 'src/common/utils/result-utils';
import { UserService } from 'src/user/user.service';
import { ChickensService } from './chickens.service';
import { CreateChickenDto } from './dto/create-chicken.dto';
import { UpdateChickenDto } from './dto/update-chicken.dto';
import { CODE } from '../common/code'
@ApiTags('小鸡主体数据接口')
@Controller('chickens')
export class ChickensController {
constructor(
private readonly chickensService: ChickensService,
private readonly userService: UserService,
) { }
//领取小鸡
@ApiOperation({ summary: '领取小鸡' })
@Post()
async create(@Body() createChickenDto: CreateChickenDto) {
//用户数据初始化
const initUser = await this.userService.init(createChickenDto)
if (!initUser) return CustomResult(CODE.CODE_INIT_USER_ERR);
//小鸡数据初始化
createChickenDto.schedule = 0;
createChickenDto.eat_start = 0;
createChickenDto.eat_end = 0;
createChickenDto.eat_time = 0;
const init = this.chickensService.create(createChickenDto);
if (!init) return CustomResult(CODE.CODE_INIT_PLAYER_ERR);
return SuccessResult(true);
}
// @Get()
// findAll() {
// return this.chickensService.findAll();
// }
// @Get(':id')
// findOne(@Param('id') id: string) {
// return this.chickensService.findOne(+id);
// }
// @Patch(':id')
// update(@Param('id') id: string, @Body() updateChickenDto: UpdateChickenDto) {
// return this.chickensService.update(+id, updateChickenDto);
// }
// @Delete(':id')
// remove(@Param('id') id: string) {
// return this.chickensService.remove(+id);
// }
}

View File

@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { ChickensService } from './chickens.service';
import { ChickensController } from './chickens.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ChickenEntity } from './entities/chicken.entity';
import { UserModule } from 'src/user/user.module';
@Module({
imports: [
TypeOrmModule.forFeature([ChickenEntity]),
UserModule,
],
controllers: [ChickensController],
exports: [ChickensService],
providers: [ChickensService]
})
export class ChickensModule { }

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChickensService } from './chickens.service';
describe('ChickensService', () => {
let service: ChickensService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChickensService],
}).compile();
service = module.get<ChickensService>(ChickensService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,36 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateChickenDto } from './dto/create-chicken.dto';
import { UpdateChickenDto } from './dto/update-chicken.dto';
import { ChickenEntity } from './entities/chicken.entity';
@Injectable()
export class ChickensService {
constructor(
@InjectRepository(ChickenEntity)
private readonly chickensRepository: Repository<ChickenEntity>
) { }
/**插入数据 */
async create(createChickenDto: CreateChickenDto) {
createChickenDto.create_time = new Date();
return await this.chickensRepository.save(createChickenDto);
}
findAll() {
return `This action returns all chickens`;
}
findOne(id: number) {
return `This action returns a #${id} chicken`;
}
update(id: number, updateChickenDto: UpdateChickenDto) {
return `This action updates a #${id} chicken`;
}
remove(id: number) {
return `This action removes a #${id} chicken`;
}
}

View File

@ -0,0 +1,16 @@
import { IsNotEmpty, IsNumber, IsString } from "class-validator";
export class CreateChickenDto {
@IsNotEmpty({ message: '用户ID不能为空' })
@IsNumber()
uid: number;
@IsString()
token: string;
schedule?: number;
eat_start?: number;
eat_end?: number;
eat_time?: number;
create_time?: Date;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateChickenDto } from './create-chicken.dto';
export class UpdateChickenDto extends PartialType(CreateChickenDto) {}

View File

@ -0,0 +1,47 @@
import { ChickenStatus } from "src/common/const";
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
/**小鸡主体 */
@Entity('chicken')
export class ChickenEntity {
@PrimaryGeneratedColumn()
id?: number;
@Column({ comment: '套装ID', type: 'int', default: 0 })
suitid: number;
@Column({ comment: '背景ID', type: 'int', default: 0 })
backdropid: number;
@Column({ comment: '碗中剩余饲料', type: 'bigint', default: 0 })
surplus_fodder: number;
@Column({ comment: '吃食数量', type: 'bigint', default: 0 })
eat_fodder: number;
@Column({ comment: '鸡蛋孵化度', type: 'int' })
schedule: number;
@Column({
comment: '吃食状态(wait待喂食;eating吃食中;wait_fetch待取蛋)',
type: "enum",
enum: ChickenStatus,
default: ChickenStatus.WAIT
})
status: string;
@Column({ comment: '吃食开始(喂饲料)时间', type: 'bigint' })
eat_start: number;//时间戳
@Column({ comment: '吃食结束时间', type: 'bigint' })
eat_end: number;//时间戳
@Column({ comment: '已经吃了多长时间(单位:s)', type: 'bigint' })
eat_time: number;
@CreateDateColumn({ comment: '创建时间', type: 'timestamp' })
create_time: Date;
@UpdateDateColumn({ comment: '修改时间', type: 'timestamp' })
update_time: Date;
}

39
src/common/code.ts Normal file
View File

@ -0,0 +1,39 @@
/** 错误信息code */
export const CODE = {
/** 调用APP服务接口异常 */
CODE_APP_SERVER_API_ERR: { code: 555, message: '调用APP服务接口异常!' },
/**APP信息失败-登录失效 */
CODE_APP_SERVER_TOKEN_ERR: { code: 556, message: '用户登录状态失效!' },
/** 用户信息异常code */
/**用户数据初始化失败 */
CODE_INIT_USER_ERR: { code: 601, message: '用户数据初始化失败!' },
CODE_INIT_PLAYER_ERR: { code: 602, message: '小鸡数据初始化失败!' },
/**用户信息更新失败 */
CODE_USER_UPDATE_ERR: { code: 603, message: '用户信息更新失败!' },
/**查询用户信息失败 */
CODE_USER_INFO_ERR: { code: 604, message: '查询用户信息失败!' },
/**查询用户APP信息失败 */
CODE_APPUSER_INFO_ERR: { code: 605, message: '查询用户APP信息失败!' },
/**用户余额不足 */
CODE_APPUSER_COIN_NOT_ENOUGHT_ERR: { code: 606, message: '用户余额不足!' },
/**扣减用户APP余额失败 */
CODE_APPUSER_SUB_COIN_ERR: { code: 606, message: '扣减用户APP余额失败!' },
/** 商品信息异常code */
/**商品添加失败 */
CODE_GOODS_INSERT_ERR: { code: 701, message: '商品添加失败!' },
/**商品信息查询失败 */
CODE_GOODS_INFO_ERR: { code: 702, message: '商品信息查询失败!' },
/**商品更新失败 */
CODE_GOODS_UPDATE_ERR: { code: 703, message: '商品更新失败!' },
/**商品删除失败 */
CODE_GOODS_DELETE_ERR: { code: 704, message: '商品删除失败!' },
/**商品购买失败 */
CODE_GOODS_DEAL_ERR: { code: 705, message: '商品购买失败!' },
/** 订单信息异常code */
CODE_ORDER_INSERT_ERR: { code: 801, message: '订单创建失败!' },
};

37
src/common/const.ts Normal file
View File

@ -0,0 +1,37 @@
/** 通用常量文件 */
/**用户在线状态 LEAVE/ONLINE */
export enum UserOnlieStatus {
LEAVE = 'leave',
ONLINE = 'online'
}
/**小鸡状态 WAIT/EATING/WAIT_FETCH */
export enum ChickenStatus {
WAIT = 'wait',//待喂食
EATING = 'eating',//吃食中
WAIT_FETCH = 'wait_fetch',//待取蛋
}
/** 商品类型 FODDER/BACKDROP/PROP/SUIT */
export enum GoodsTypes {
FODDER = 'fodder',//饲料
BACKDROP = 'backdrop',//背景
PROP = 'prop',//道具
SUIT = 'suit',//套装
}
/** 商品状态 selling/sellend/hide */
export enum GoodsStatus {
SELLING = 'selling',//售卖中
SELLEND = 'sellend',//售卖结束
HIDE = 'hide',//隐藏
}
/** 邀请用户获得钻石领取状态 none/received/unreceive/wait_receive */
export enum ParentReceiveStatus {
NONE = 'none',//售卖中
RECEIVED = 'received',//售卖结束
UNRECEIVE = 'unreceive',//隐藏
WAIT_RECEIVE = 'wait_receive',//隐藏
}

View File

@ -0,0 +1,43 @@
import {
ArgumentMetadata,
HttpException,
Injectable,
Logger,
PipeTransform,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class HttpValidationPipe implements PipeTransform<any> {
private logger = new Logger('HttpValidationPipe');
private code = 400;//错误自定义code
constructor(code?: number) {
// super(options)
this.code = code;
}
async transform(value: any, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
this.logger.debug('HttpValidationPipe.start' + JSON.stringify(value));
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
const error = errors[0];
throw new HttpException(
`请求参数不合法:${error.value};${JSON.stringify(error.constraints)}`,
this.code,
); //new BadRequestException('Validation failed');
}
return object;
}
// eslint-disable-next-line @typescript-eslint/ban-types
private toValidate(metatype: Function): boolean {
// eslint-disable-next-line @typescript-eslint/ban-types
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}

View File

@ -0,0 +1,70 @@
/**
* 访API接口
*/
import { Logger } from "@nestjs/common";
import { AppUserModel } from "src/user/user.model";
import { CODE } from "../code";
import { httpGetRequest } from "./http-utils";
import { CustomResult, SuccessResult } from "./result-utils";
export class ExternalApiService {
static logger = new Logger('ExternalApiService');
/**获取APP用户信息 */
static async getAppUserInfo(uid: number, token: string): Promise<AppUserModel | any> {
try {
const res = await httpGetRequest('Appapi/cash/getuser', { uid: uid, token: token });
if (res.code == 0) {
const data = res.info;
const user = {
id: data.id,
nickname: data.user_nicename,
avatar: data.avatar,
sex: data.sex,
mobile: data.mobile,
coin: data.coin,
level: data.level,
risk: data.risk
}
return SuccessResult(user);
}
if (res?.code == 700) return CustomResult(CODE.CODE_APP_SERVER_TOKEN_ERR);
this.logger.debug(`获取APP用户信息失败,app返回结果: ${JSON.stringify(res)}`);
return CustomResult(CODE.CODE_APPUSER_INFO_ERR);
} catch (e) {
this.logger.debug(`调用APP接口异常: ${JSON.stringify(e)}`);
return CustomResult(CODE.CODE_APP_SERVER_API_ERR);
}
}
/**APP用户金额扣减 */
static async subAppUserCoin(uid: number, token: string, value: number): Promise<AppUserModel | any> {
try {
const subRes = await httpGetRequest('Appapi/cash/getuser', { uid: uid, token: token, amount: -1 * value });
this.logger.debug(`扣减用户信息返回结果:${JSON.stringify(subRes)}`);
if (subRes.code == 0) {
const data = subRes.info;
const user = {
id: data.id,
nickname: data.user_nicename,
avatar: data.avatar,
sex: data.sex,
mobile: data.mobile,
coin: data.coin,
level: data.level,
risk: data.risk
}
return SuccessResult(user);
}
if (subRes?.code == 700) return CustomResult(CODE.CODE_APP_SERVER_TOKEN_ERR);
this.logger.debug(`扣减用户APP余额失败,app返回结果: ${JSON.stringify(subRes)}`);
return CustomResult(CODE.CODE_APPUSER_SUB_COIN_ERR);
} catch (e) {
this.logger.debug(`调用APP接口异常: ${JSON.stringify(e)}`);
return CustomResult(CODE.CODE_APP_SERVER_API_ERR);
}
}
}

View File

@ -0,0 +1,20 @@
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}

View File

@ -0,0 +1,100 @@
/**
* http请求封装
*/
import fetch from 'node-fetch';
const host = 'http://app.worknote.xyz/';
const sign = '123321';
/**http GET请求 */
export async function httpGetRequest(url: string, params: any) {
const options = {
method: 'GET'
}
if (params) {
params['sign'] = sign;//追加签名
url += "?";
for (var key in params) {
url += `${key}=${params[key]}&`;
}
}
url = url.replace(/&{1}$/, ''); // 去掉最后一个拼接的&
return fetch(host + url, options)
.then(response => {
// fetch与ajax(axios)不同,只要服务器有返回值,都是成功,没有返回值才算失败。
// 所以要在这里进行处理所有返回的结果
if (!/^(2|3)\d{2}$/.test(String(response.status))) {
// 失败的状态非2|3开头的状态进行处理
switch (response.status) {
case 401:
// 权限不够,一般是未登录
// ...
break;
case 403:
// 服务器已经接受,但是拒绝访问,通常是登录过期
// ...
localStorage.removeItem("token");
break;
case 404:
// 找不到资源
// ...
break;
}
}
// 处理之后将response的所有数据转换成json客户端就可以拿到以json格式响应的所有数据
return response.json();
})
.catch(error => {
// 服务器没有响应才会跳转到这里
if (!window.navigator.onLine) {
// 断网处理
// ...
return;
}
// 什么都没有,返回一个错误
return Promise.reject(error);
});
}
/**http POST请求 */
export async function httpPostRequest(url: string, params: any) {
const options = {
method: 'POST',
body: params
}
return fetch(host + url + `?sign=${sign}`, options)
.then(response => {
// fetch与ajax(axios)不同,只要服务器有返回值,都是成功,没有返回值才算失败。
// 所以要在这里进行处理所有返回的结果
if (!/^(2|3)\d{2}$/.test(String(response.status))) {
// 失败的状态非2|3开头的状态进行处理
switch (response.status) {
case 401:
// 权限不够,一般是未登录
// ...
break;
case 403:
// 服务器已经接受,但是拒绝访问,通常是登录过期
// ...
localStorage.removeItem("token");
break;
case 404:
// 找不到资源
// ...
break;
}
}
// 处理之后将response的所有数据转换成json客户端就可以拿到以json格式响应的所有数据
return Promise.resolve(response.json());
})
.catch(error => {
// 服务器没有响应才会跳转到这里
if (!window.navigator.onLine) {
// 断网处理
// ...
return;
}
// 什么都没有,返回一个错误
return Promise.reject(error);
});
}

View File

@ -0,0 +1,54 @@
export const LOG4JS_NO_COLOUR_DEFAULT_LAYOUT = {
type: 'pattern',
// log4js default pattern %d{yyyy-MM-dd HH:mm:ss:SSS} [%thread] %-5level %logger{36} - %msg%n
// we use process id instead thread id
pattern:
'%d{yyyy-MM-dd hh:mm:ss:SSS} %p --- [%15.15x{name}] %40.40f{3} : %m',
tokens: {
name: (logEvent) => {
return (logEvent.context && logEvent.context['name']) || '-';
},
},
};
export const LOG4JS_DEFAULT_LAYOUT = {
type: 'pattern',
// log4js default pattern %d{yyyy-MM-dd HH:mm:ss:SSS} [%thread] %-5level %logger{36} - %msg%n
// we use process id instead thread id
pattern:
'%[%d{yyyy-MM-dd hh:mm:ss:SSS} %p --- [%20.20x{name}]%] %20.40f{3} : %m',
tokens: {
name: (logEvent) => {
return (logEvent.context && logEvent.context['name']) || '-';
},
},
};
export default {
appenders: {
app: {
type: 'dateFile',
pattern: '.yyyy-MM-dd-hh',
filename: 'logs/app.log',
layout: LOG4JS_NO_COLOUR_DEFAULT_LAYOUT,
categorie: ['app'],
},
coinlog_file: {
type: 'dateFile',
pattern: '.yyyy-MM-dd-hh',
filename: 'logs/coin.log',
layout: LOG4JS_NO_COLOUR_DEFAULT_LAYOUT,
categorie: ['coinlog'],
},
consoleout: { type: 'console', layout: LOG4JS_DEFAULT_LAYOUT },
},
categories: {
coinlog: {
appenders: ['coinlog_file'],
level: 'all',
},
default: {
appenders: ['consoleout', 'app'],
level: 'all',
},
},
};

View File

@ -0,0 +1,53 @@
import { HttpException } from "@nestjs/common";
/**
*
* @data
* @pageIndex
* @pageSize
* @count
*/
export function DataListResult(data: any[], pageIndex: number, pageSize: number, count: number) {
return {
dataList: data,
pageInfo: {
totalItems: Number(count),//总条数
totalPages: (count > 0 ? (Math.floor(count / pageSize) == 0 ? 1 : Math.floor(count / pageSize)) : 1),//总页数
currentPage: pageIndex,//当前页
itemCount: data.length,//每页数量
itemsPerPage: pageSize//输入的每页条数
}
};
}
/**
*
* @code
* @message
*/
export function CustomResult(params: { code: number, message: string }) {
return { code: params.code, message: params.message };
// throw new HttpException({
// code: params.code,
// error: params.message,
// }, params.code);
}
/**
*
* @code
* @message
*/
export function SuccessResult(data?: any) {
return { code: 200, data: data, message: '请求成功' }
}
export interface ErrResultModel {
code: number,
message: string
}
export interface DataResultModel {
code: number,
data: any,
message: string
}

10
src/config/config.yml Normal file
View File

@ -0,0 +1,10 @@
database:
host: '127.0.0.1'
port: 3306
dbname: 'chick_game'
username: 'root'
password: '123456'
drop_schema: false #启动程序时全部删除并重建数据表(生产环境严禁启用)
charset: utf8mb4 #数据库编码
synchronize: true #自动同步表结构
port: 8888

View File

@ -0,0 +1,15 @@
import * as fs from 'fs';
import * as yaml from 'js-yaml';
import * as path from 'path';
const YAML_CONFIG_FILENAME = path.resolve(
process.env.config_path || path.join(__dirname, 'config.yml'),
);
console.log('=========== config.yml =========');
console.log(YAML_CONFIG_FILENAME);
console.log('=========== config.yml =========');
export default () => {
return yaml.load(
fs.readFileSync(YAML_CONFIG_FILENAME, 'utf8'),
) as Record<string, any>;
};

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigurationController } from './configuration.controller';
import { ConfigurationService } from './configuration.service';
describe('ConfigurationController', () => {
let controller: ConfigurationController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ConfigurationController],
providers: [ConfigurationService],
}).compile();
controller = module.get<ConfigurationController>(ConfigurationController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,34 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { ConfigurationService } from './configuration.service';
import { CreateConfigurationDto } from './dto/create-configuration.dto';
import { UpdateConfigurationDto } from './dto/update-configuration.dto';
@Controller('configuration')
export class ConfigurationController {
constructor(private readonly configurationService: ConfigurationService) {}
// @Post()
// create(@Body() createConfigurationDto: CreateConfigurationDto) {
// return this.configurationService.create(createConfigurationDto);
// }
// @Get()
// findAll() {
// return this.configurationService.findAll();
// }
// @Get(':id')
// findOne(@Param('id') id: string) {
// return this.configurationService.findOne(+id);
// }
// @Patch(':id')
// update(@Param('id') id: string, @Body() updateConfigurationDto: UpdateConfigurationDto) {
// return this.configurationService.update(+id, updateConfigurationDto);
// }
// @Delete(':id')
// remove(@Param('id') id: string) {
// return this.configurationService.remove(+id);
// }
}

View File

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ConfigurationService } from './configuration.service';
import { ConfigurationController } from './configuration.controller';
@Module({
controllers: [ConfigurationController],
providers: [ConfigurationService]
})
export class ConfigurationModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigurationService } from './configuration.service';
describe('ConfigurationService', () => {
let service: ConfigurationService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ConfigurationService],
}).compile();
service = module.get<ConfigurationService>(ConfigurationService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateConfigurationDto } from './dto/create-configuration.dto';
import { UpdateConfigurationDto } from './dto/update-configuration.dto';
@Injectable()
export class ConfigurationService {
create(createConfigurationDto: CreateConfigurationDto) {
return 'This action adds a new configuration';
}
findAll() {
return `This action returns all configuration`;
}
findOne(id: number) {
return `This action returns a #${id} configuration`;
}
update(id: number, updateConfigurationDto: UpdateConfigurationDto) {
return `This action updates a #${id} configuration`;
}
remove(id: number) {
return `This action removes a #${id} configuration`;
}
}

View File

@ -0,0 +1 @@
export class CreateConfigurationDto {}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateConfigurationDto } from './create-configuration.dto';
export class UpdateConfigurationDto extends PartialType(CreateConfigurationDto) {}

View File

@ -0,0 +1 @@
export class Configuration {}

View File

@ -0,0 +1,30 @@
import { IsNotEmpty, IsDate, IsString, IsInt, IsIn } from "class-validator";
import { GoodsStatus, GoodsTypes } from "src/common/const";
export class CreateGoodDto {
@IsNotEmpty({ message: '类型不能为空' })
@IsIn(Object.values(GoodsTypes))
type: string;
@IsString()
name: string;
@IsString()
desc: string;
@IsString()
image: string;
@IsInt()
price: number;
@IsInt()
attribute: number;
@IsString()
@IsIn(Object.values(GoodsStatus))
status: string;
create_time?: Date;
update_time?: Date;
}

View File

@ -0,0 +1,31 @@
import { PartialType } from '@nestjs/swagger';
import { CreateGoodDto } from './create-good.dto';
import { IsNotEmpty, IsString, IsInt, IsIn } from "class-validator";
import { GoodsStatus, GoodsTypes } from "src/common/const";
export class UpdateGoodDto extends PartialType(CreateGoodDto) {
@IsNotEmpty({ message: '类型不能为空' })
@IsIn(Object.values(GoodsTypes))
type: string;
@IsString()
name: string;
@IsString()
desc: string;
@IsString()
image: string;
@IsInt()
price: number;
@IsInt()
attribute: number;
@IsString()
@IsIn(Object.values(GoodsStatus))
status: string;
update_time?: Date;
}

View File

@ -0,0 +1,46 @@
import { GoodsStatus, GoodsTypes } from "src/common/const";
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
/**商城商品主体 */
@Entity('goods')
export class GoodsEntity {
@PrimaryGeneratedColumn()
id?: number;
@Column({
comment: '商品类型(fodder-饲料;backdrop-背景;prop-道具;suit-套装)',
type: "enum",
enum: GoodsTypes,
default: GoodsTypes.FODDER
})
type: string;
@Column({ comment: '商品名', type: 'varchar', default: '' })
name: string;
@Column({ comment: '商品描述', type: 'varchar', default: '' })
desc: string;
@Column({ comment: '商品图片', type: 'varchar', default: '' })
image: string;
@Column({ comment: '价格', type: 'bigint' })
price: number;
@Column({ comment: '属性(如:饲料(克),背景/道具/套装(天)', type: 'bigint' })
attribute: number;
@Column({
comment: '商品状态(selling-售卖中;sellend-售卖结束;hide-隐藏)',
type: "enum",
enum: GoodsStatus,
default: GoodsStatus.HIDE
})
status: string;
@CreateDateColumn({ comment: '创建时间', type: 'timestamp' })
create_time: Date;
@UpdateDateColumn({ comment: '修改时间', type: 'timestamp' })
update_time: Date;
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { GoodsController } from './goods.controller';
import { GoodsService } from './goods.service';
describe('GoodsController', () => {
let controller: GoodsController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [GoodsController],
providers: [GoodsService],
}).compile();
controller = module.get<GoodsController>(GoodsController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,57 @@
import { Controller, Get, Param, Query, UsePipes } from '@nestjs/common';
import { GoodsService } from './goods.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { HttpValidationPipe } from 'src/common/utils/HttpValidationPipe';
import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator';
import { GoodsStatus, GoodsTypes } from 'src/common/const';
import { GoodsListModel } from './goods.model';
import { SuccessResult } from 'src/common/utils/result-utils';
@ApiTags('商品数据接口')
@Controller('goods')
export class GoodsController {
constructor(private readonly goodsService: GoodsService) { }
//商品列表
@ApiOperation({ summary: '商品列表' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'pageIndex',
required: true,
description: '当前页',
type: Number,
})
@ApiImplicitQuery({
name: 'pageSize',
required: true,
description: '分页',
type: Number,
})
@Get()
async goodsList(@Query() query: GoodsListModel) {
let returnData: any = {};
//循环商品类型
const goodsTypes = Object.values(GoodsTypes);
for (let i = 0; i < goodsTypes.length; i++) {
query.type = goodsTypes[i];
const goods = await this.goodsService.apiGoodsList(query)
returnData[goodsTypes[i]] = goods;
}
return SuccessResult(returnData);
}
//商品查询
@ApiOperation({ summary: '商品查询' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'id',
required: true,
description: '商品ID',
type: Number,
})
@Get(':id')
async findOne(@Query('id') id: number) {
return this.goodsService.findOne(+id, GoodsStatus.HIDE);
}
}

11
src/goods/goods.model.ts Normal file
View File

@ -0,0 +1,11 @@
/**商品列表查询参数 */
export interface GoodsListModel {
pageIndex: number,
pageSize: number,
keywords?: string,
/**商品状态 selling-售卖中;sellend-售卖结束;hide-隐藏 */
status?: string,
/**商品状态 fodder-饲料;backdrop-背景;prop-道具;suit-套装 */
type?: string,
}

13
src/goods/goods.module.ts Normal file
View File

@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { GoodsService } from './goods.service';
import { GoodsController } from './goods.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GoodsEntity } from './entities/good.entity';
@Module({
imports: [TypeOrmModule.forFeature([GoodsEntity])],
controllers: [GoodsController],
exports:[GoodsService],
providers: [GoodsService]
})
export class GoodsModule { }

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { GoodsService } from './goods.service';
describe('GoodsService', () => {
let service: GoodsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [GoodsService],
}).compile();
service = module.get<GoodsService>(GoodsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,86 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CODE } from 'src/common/code';
import { GoodsStatus, GoodsTypes } from 'src/common/const';
import { CustomResult, DataListResult, SuccessResult } from 'src/common/utils/result-utils';
import { Repository } from 'typeorm';
import { CreateGoodDto } from './dto/create-good.dto';
import { UpdateGoodDto } from './dto/update-good.dto';
import { GoodsEntity } from './entities/good.entity';
import { GoodsListModel } from './goods.model';
const prefix = 'goods';
@Injectable()
export class GoodsService {
constructor(
@InjectRepository(GoodsEntity)
private readonly goodsRepository: Repository<GoodsEntity>,
) { }
/**插入数据 */
async create(createGoodDto: CreateGoodDto) {
createGoodDto.type = createGoodDto.type || GoodsTypes.FODDER;
createGoodDto.create_time = new Date();
createGoodDto.update_time = new Date();
const res = await this.goodsRepository.save(createGoodDto);
if (!res) return CustomResult(CODE.CODE_GOODS_INSERT_ERR);
return SuccessResult(res);
}
/** 查询所有-列表 */
async goodsList(params: GoodsListModel) {
let findBuilder = this.goodsRepository.createQueryBuilder(prefix);
const limit = (params.pageIndex - 1 > 0 ? params.pageIndex - 1 : 0) * params.pageSize;
//商品状态(API接口排除隐藏的)
if (params.status) findBuilder = findBuilder.andWhere(`status != :status`, { status: params.status });
const res = await findBuilder
.select().skip(limit).take(params.pageSize).getRawMany();
const total = await findBuilder.select().getCount();
return DataListResult(res, params.pageIndex, params.pageSize, total);
}
/** 查询商品详情 */
async findOne(id: number, status?: string) {
let findBuilder = this.goodsRepository.createQueryBuilder(prefix);
//商品状态(API接口排除隐藏的)
if (status) findBuilder = findBuilder.andWhere(`status != :status`, { status: status });
const returnData = await findBuilder.select().andWhere(`id=:id`, { id: id }).getRawOne();
if (!returnData) return CustomResult(CODE.CODE_GOODS_INFO_ERR);
return SuccessResult(returnData);
}
/** 商品更新 */
async updateGoods(id: number, updateGoodDto: UpdateGoodDto) {
updateGoodDto.update_time = new Date();
const res = await this.goodsRepository.createQueryBuilder()
.update()
.set(updateGoodDto)
.where('id = :id', { id: id })
.execute();
if (!res) return CustomResult(CODE.CODE_GOODS_UPDATE_ERR)
return SuccessResult();
}
/** 商品删除 */
async remove(id: number) {
const res = await this.goodsRepository.createQueryBuilder()
.delete()
.where('id = :id', { id: id })
.execute();
if (!res || res.raw.affectedRows == 0) return CustomResult(CODE.CODE_GOODS_DELETE_ERR);
return SuccessResult();
}
/** API 查询所有-列表 */
async apiGoodsList(params: GoodsListModel) {
let findBuilder = this.goodsRepository.createQueryBuilder(prefix);
// const limit = (params.pageIndex - 1 > 0 ? params.pageIndex - 1 : 0) * params.pageSize;
//商品状态(API接口排除隐藏的)
const res = await findBuilder
.select()
.andWhere(`status != :status AND type = :type`, { status: GoodsStatus.HIDE, type: params.type })
.getRawMany();
// const total = await findBuilder.select().getCount();
return res;
}
}

View File

@ -0,0 +1 @@
export class CreateInvitedstatisticDto {}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateInvitedstatisticDto } from './create-invitedstatistic.dto';
export class UpdateInvitedstatisticDto extends PartialType(CreateInvitedstatisticDto) {}

View File

@ -0,0 +1,28 @@
import { Column, CreateDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
/** 邀请人统计实体 */
export class Invitedstatistic {
@PrimaryGeneratedColumn()
id: number;
@Column({ comment: '用户ID', type: 'bigint' })
userid: number;
@Column({ comment: '当前有效人数', type: 'bigint', default: 0 })
current_valid_count: number;
@Column({ comment: '无效人数', type: 'bigint', default: 0 })
current_invalid_count: number;
@Column({ comment: '已领取钻石', type: 'bigint', default: 0 })
received_balance: number;
@Column({ comment: '待领取钻石', type: 'bigint', default: 0 })
wait_receive_balance: number;
@CreateDateColumn({ comment: '创建时间', type: 'timestamp' })
create_time: Date;
@UpdateDateColumn({ comment: '修改时间', type: 'timestamp' })
update_time: Date;
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { InvitedstatisticsController } from './invitedstatistics.controller';
import { InvitedstatisticsService } from './invitedstatistics.service';
describe('InvitedstatisticsController', () => {
let controller: InvitedstatisticsController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [InvitedstatisticsController],
providers: [InvitedstatisticsService],
}).compile();
controller = module.get<InvitedstatisticsController>(InvitedstatisticsController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,36 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { InvitedstatisticsService } from './invitedstatistics.service';
import { CreateInvitedstatisticDto } from './dto/create-invitedstatistic.dto';
import { UpdateInvitedstatisticDto } from './dto/update-invitedstatistic.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('邀请人统计接口')
@Controller('invitedstatistics')
export class InvitedstatisticsController {
constructor(private readonly invitedstatisticsService: InvitedstatisticsService) {}
@Post()
create(@Body() createInvitedstatisticDto: CreateInvitedstatisticDto) {
return this.invitedstatisticsService.create(createInvitedstatisticDto);
}
@Get()
findAll() {
return this.invitedstatisticsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.invitedstatisticsService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateInvitedstatisticDto: UpdateInvitedstatisticDto) {
return this.invitedstatisticsService.update(+id, updateInvitedstatisticDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.invitedstatisticsService.remove(+id);
}
}

View File

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { InvitedstatisticsService } from './invitedstatistics.service';
import { InvitedstatisticsController } from './invitedstatistics.controller';
@Module({
controllers: [InvitedstatisticsController],
providers: [InvitedstatisticsService]
})
export class InvitedstatisticsModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { InvitedstatisticsService } from './invitedstatistics.service';
describe('InvitedstatisticsService', () => {
let service: InvitedstatisticsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [InvitedstatisticsService],
}).compile();
service = module.get<InvitedstatisticsService>(InvitedstatisticsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateInvitedstatisticDto } from './dto/create-invitedstatistic.dto';
import { UpdateInvitedstatisticDto } from './dto/update-invitedstatistic.dto';
@Injectable()
export class InvitedstatisticsService {
create(createInvitedstatisticDto: CreateInvitedstatisticDto) {
return 'This action adds a new invitedstatistic';
}
findAll() {
return `This action returns all invitedstatistics`;
}
findOne(id: number) {
return `This action returns a #${id} invitedstatistic`;
}
update(id: number, updateInvitedstatisticDto: UpdateInvitedstatisticDto) {
return `This action updates a #${id} invitedstatistic`;
}
remove(id: number) {
return `This action removes a #${id} invitedstatistic`;
}
}

37
src/main.ts Normal file
View File

@ -0,0 +1,37 @@
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AdminModule } from './admin/admin.module';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const httpPort = configService.get<string>('port');
console.log(`Linsten port http://192.168.60.11:${httpPort}`);
//swagger
const options = new DocumentBuilder()
.setTitle('【 API 】小鸡游戏接口')
.setDescription('客户端接口文档')
.setVersion('1.2.2')
.build();
const apiDocument = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, apiDocument);
console.log(`swagger http://192.168.60.11:${httpPort}/api`);
const adminOptions = new DocumentBuilder()
.setTitle('【 Admin 】小鸡游戏管理接口')
.setDescription('管理后台接口文档')
.setVersion('1.2.2')
.build();
const adminDocument = SwaggerModule.createDocument(app, adminOptions, {
include: [AdminModule]
});
SwaggerModule.setup('admin', app, adminDocument);
console.log(`swagger admin http://192.168.60.11:${httpPort}/admin`);
await app.listen(httpPort);
}
bootstrap();

View File

@ -0,0 +1,28 @@
import { IsNotEmpty, IsInt, IsIn } from "class-validator";
import { GoodsTypes } from "src/common/const";
export class CreateOrderlogDto {
@IsNotEmpty({ message: '类型不能为空' })
@IsIn(Object.values(GoodsTypes))
goods_type: string;
@IsNotEmpty({ message: '用户ID不能为空' })
@IsInt()
userid: number;
@IsNotEmpty({ message: '商品ID不能为空' })
@IsInt()
goods_id: number;
@IsNotEmpty({ message: '商品价格不能为空' })
@IsInt()
goods_price: number;
@IsNotEmpty({ message: '商品属性不能为空' })
@IsInt()
goods_attribute: number;
buy_time?: Date;
create_time?: Date;
update_time?: Date;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateOrderlogDto } from './create-orderlog.dto';
export class UpdateOrderlogDto extends PartialType(CreateOrderlogDto) {}

View File

@ -0,0 +1,39 @@
import { GoodsTypes } from "src/common/const";
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
/** 订单主体 */
@Entity('orderlog')
export class OrderlogEntity {
@PrimaryGeneratedColumn('uuid')
orderid: string;
@Column({ comment: '用户ID', type: 'bigint', default: 0 })
userid: number;
@Column({ comment: '商品ID', type: 'bigint', default: 0 })
goods_id: number;
@Column({
comment: '商品类型(fodder-饲料;backdrop-背景;prop-道具;suit-套装)',
type: "enum",
enum: GoodsTypes,
default: GoodsTypes.FODDER
})
goods_type: string;
@Column({ comment: '商品价格(购买时)', type: 'bigint' })
goods_price: number;
@Column({ comment: '商品属性(如:饲料(克),背景/道具/套装(天)', type: 'bigint' })
goods_attribute: number;
@CreateDateColumn({ comment: '购买时间', type: 'timestamp' })
buy_time: Date;
@CreateDateColumn({ comment: '创建时间', type: 'timestamp' })
create_time: Date;
@UpdateDateColumn({ comment: '修改时间', type: 'timestamp' })
update_time: Date;
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { OrderlogController } from './orderlog.controller';
import { OrderlogService } from './orderlog.service';
describe('OrderlogController', () => {
let controller: OrderlogController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [OrderlogController],
providers: [OrderlogService],
}).compile();
controller = module.get<OrderlogController>(OrderlogController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,36 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { OrderlogService } from './orderlog.service';
import { CreateOrderlogDto } from './dto/create-orderlog.dto';
import { UpdateOrderlogDto } from './dto/update-orderlog.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('购买信息数据接口')
@Controller('orderlog')
export class OrderlogController {
constructor(private readonly orderlogService: OrderlogService) {}
@Post()
create(@Body() createOrderlogDto: CreateOrderlogDto) {
return this.orderlogService.create(createOrderlogDto);
}
@Get()
findAll() {
return this.orderlogService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.orderlogService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateOrderlogDto: UpdateOrderlogDto) {
return this.orderlogService.update(+id, updateOrderlogDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.orderlogService.remove(+id);
}
}

View File

@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { OrderlogService } from './orderlog.service';
import { OrderlogController } from './orderlog.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { OrderlogEntity } from './entities/orderlog.entity';
@Module({
imports: [TypeOrmModule.forFeature([OrderlogEntity])],
controllers: [OrderlogController],
exports: [OrderlogService],
providers: [OrderlogService]
})
export class OrderlogModule { }

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { OrderlogService } from './orderlog.service';
describe('OrderlogService', () => {
let service: OrderlogService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [OrderlogService],
}).compile();
service = module.get<OrderlogService>(OrderlogService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,42 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CODE } from 'src/common/code';
import { CustomResult, SuccessResult } from 'src/common/utils/result-utils';
import { Repository } from 'typeorm';
import { CreateOrderlogDto } from './dto/create-orderlog.dto';
import { UpdateOrderlogDto } from './dto/update-orderlog.dto';
import { OrderlogEntity } from './entities/orderlog.entity';
@Injectable()
export class OrderlogService {
constructor(
@InjectRepository(OrderlogEntity)
private readonly orderLogRepository: Repository<OrderlogEntity>,
) { }
/** 创建 */
async create(createOrderlogDto: CreateOrderlogDto) {
createOrderlogDto.buy_time = new Date();
createOrderlogDto.create_time = new Date();
createOrderlogDto.update_time = new Date();
const res = await this.orderLogRepository.save(createOrderlogDto);
if (res?.orderid) return SuccessResult(res);
return CustomResult(CODE.CODE_ORDER_INSERT_ERR);
}
findAll() {
return `This action returns all orderlog`;
}
findOne(id: number) {
return `This action returns a #${id} orderlog`;
}
update(id: number, updateOrderlogDto: UpdateOrderlogDto) {
return `This action updates a #${id} orderlog`;
}
remove(id: number) {
return `This action removes a #${id} orderlog`;
}
}

0
src/redis/cache.ts Normal file
View File

View File

@ -0,0 +1,19 @@
import { IsInt, IsNotEmpty, IsString } from 'class-validator';
export class BuyGoodsUserDto {
@IsNotEmpty({ message: '用户ID不能为空' })
@IsInt()
userid: number;
@IsNotEmpty({ message: '用户token不能为空' })
@IsString()
token: string;
@IsNotEmpty({ message: '用户购买商品ID不能为空' })
@IsInt()
goodsid: number;
@IsNotEmpty({ message: '用户购买商品商品数量不能为空' })
@IsInt()
goods_count: number;
}

View File

@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
export class CreateUserDto {
@ApiProperty()
token: string;
@ApiProperty()
uid: number;
}

View File

@ -0,0 +1,12 @@
import { PartialType } from '@nestjs/mapped-types';
import { IsIn, IsNotEmpty } from 'class-validator';
import { UserOnlieStatus } from 'src/common/const';
import { CreateUserDto } from './create-user.dto';
export class UpdateUserDto extends PartialType(CreateUserDto) {
@IsNotEmpty({ message: '用户状态不能为空' })
@IsIn(Object.values(UserOnlieStatus))
online_status: string;
update_time?:Date;
}

View File

@ -0,0 +1,60 @@
import { ParentReceiveStatus, UserOnlieStatus } from "src/common/const";
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
/**游戏用户主体 */
@Entity('user')
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ comment: '用户ID', type: 'bigint' })
userid: number;
@Column({ comment: '用户头像', type: 'varchar', default: '' })
avatar: string;//头像每次进游戏更新
@Column({ comment: '用户昵称', type: 'varchar', default: '' })
nickname: string;//昵称每次进游戏更新
@Column({ comment: '饲料余额', type: 'bigint', default: 0 })
fodder_balance: number;
@Column({ comment: '已有鸡蛋数量', type: 'bigint', default: 0 })
eggs: number;
@Column({
comment: '在线状态',
type: "enum",
enum: UserOnlieStatus,
default: UserOnlieStatus.LEAVE
})
online_status: string;
// @Column({ comment: '上级用户ID', type: 'bigint' })
// parent_id: number;
// @Column({ comment: '父级从中获取钻石数量', type: 'bigint' })
// parent_gain: number;
// @Column({
// comment: '钻石领取状态(none-无;received-已领取;unreceive-未领取;wait_receive-n天后领取)',
// type: "enum",
// enum: ParentReceiveStatus,
// default: ParentReceiveStatus.NONE
// })
// parent_gain_status: string;
// @Column({ comment: '父级盈利领取时间', type: 'varchar', default: '' })
// parent_gain_time: string;
// @Column({ comment: '父级盈利失败原因', type: 'varchar', default: '' })
// parent_gain_reason: string;
// @Column({ comment: 'APP注册时间', type: 'varchar', default: '' })
// register_time: string;
@CreateDateColumn({ comment: '游戏玩家信息创建时间', type: 'timestamp' })
create_time: Date;
@UpdateDateColumn({ comment: '修改时间', type: 'timestamp' })
update_time: Date;
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';
describe('UserController', () => {
let controller: UserController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService],
}).compile();
controller = module.get<UserController>(UserController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,44 @@
import { Controller, Get, Body, Patch, Param, UsePipes, Query, Post } from '@nestjs/common';
import { UserService } from './user.service';
import { UpdateUserDto } from './dto/update-user.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { SuccessResult } from 'src/common/utils/result-utils';
import { HttpValidationPipe } from 'src/common/utils/HttpValidationPipe';
import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator';
import { BuyGoodsUserDto } from './dto/buygoods-user.dto';
@ApiTags('用户数据接口')
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) { }
//查询用户信息
@ApiOperation({ summary: '用户信息查询' })
@Get(':userid')
async findOne(@Param('userid') userid: number) {
return SuccessResult(await this.userService.findOne(userid));
}
//更新用户在线状态
@ApiOperation({ summary: '更新用户在线状态' })
@UsePipes(new HttpValidationPipe())
@ApiImplicitQuery({
name: 'userid',
required: true,
description: '当前用户ID',
type: Number,
})
@Patch(':userid')
async update(@Query('userid') userid: number, @Body() updateUserDto: UpdateUserDto) {
return this.userService.update(+userid, updateUserDto);
}
//TODO 购买商品
@ApiOperation({ summary: '购买商品' })
@UsePipes(new HttpValidationPipe())
@Post('buy')
async buy(@Body() buyGoodsUserDto: BuyGoodsUserDto) {
return await this.userService.buy(buyGoodsUserDto);
}
}

24
src/user/user.model.ts Normal file
View File

@ -0,0 +1,24 @@
/**APP用户信息 */
export interface AppUserModel {
id: number,
nickname: string,
avatar: string,
sex: number,
mobile: number,
coin: number,
level: number,
risk: number
}
/**游戏用户信息 */
export interface UserModel {
id?: number,
userid: number,
avatar: string,
nickname: string,
fodder_balance: number,
eggs: number,
online_status: string,
parent_id: number,
create_time: Date,
update_time: Date,
}

21
src/user/user.module.ts Normal file
View File

@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { GoodsService } from 'src/goods/goods.service';
import { GoodsEntity } from 'src/goods/entities/good.entity';
import { OrderlogEntity } from 'src/orderlog/entities/orderlog.entity';
import { OrderlogService } from 'src/orderlog/orderlog.service';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule,
TypeOrmModule.forFeature([UserEntity, GoodsEntity, OrderlogEntity])
],
controllers: [UserController],
exports: [UserService],
providers: [UserService, GoodsService, OrderlogService]
})
export class UserModule { }

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

119
src/user/user.service.ts Normal file
View File

@ -0,0 +1,119 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CODE } from 'src/common/code';
import { GoodsStatus, UserOnlieStatus } from 'src/common/const';
import { ExternalApiService } from 'src/common/utils/external-api';
import { CustomResult, SuccessResult } from 'src/common/utils/result-utils';
import { GoodsService } from 'src/goods/goods.service';
import { CreateOrderlogDto } from 'src/orderlog/dto/create-orderlog.dto';
import { OrderlogService } from 'src/orderlog/orderlog.service';
import { Repository } from 'typeorm';
import { BuyGoodsUserDto } from './dto/buygoods-user.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserEntity } from './entities/user.entity';
import { UserModel, AppUserModel } from './user.model';
const prefix = 'user';
const logger = new Logger('UserService');
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
private readonly goodsService: GoodsService,
private readonly orderLogService: OrderlogService
) { }
/**查询用户信息,没有则初始化 */
async init(createUserDto: CreateUserDto) {
//查询用户信息
const userInfo = await this.findOne(createUserDto.uid);
//有信息则返回
const appUserInfo = await ExternalApiService.getAppUserInfo(createUserDto.uid, createUserDto.token);
if (userInfo) return userInfo;
//用户信息异常处理
if (!appUserInfo || appUserInfo.code != 200) return CustomResult(CODE.CODE_USER_INFO_ERR);
//没有信息则初始化
const initRes = await this.initUser(appUserInfo);
if (!initRes) return CustomResult(CODE.CODE_INIT_USER_ERR);
return initRes;
}
/**用户信息初始化 */
private async initUser(appUser: AppUserModel) {
const entity: UserModel = {
userid: appUser.id,
avatar: appUser.avatar,
nickname: appUser.nickname,
fodder_balance: 0,
eggs: 0,
online_status: UserOnlieStatus.ONLINE,
parent_id: 0,
create_time: new Date(),
update_time: new Date()
}
return await this.userRepository.save(entity);
}
/**查询用户信息 */
async findOne(userid: number) {
const info = await this.userRepository.createQueryBuilder(prefix)
.select()
.where('userid = :userid', { userid: userid })
.getRawOne();
return info;
}
/**更新用户数据 */
async update(userid: number, updateUserDto: UpdateUserDto) {
updateUserDto.update_time = new Date();
const res = await this.userRepository.createQueryBuilder()
.update()
.set(updateUserDto)
.where('userid = :userid', { userid: userid })
.execute();
if (!res) return CustomResult(CODE.CODE_USER_UPDATE_ERR)
return SuccessResult();
}
/** 用户购买商品逻辑 */
async buy(buyGoodsUserDto: BuyGoodsUserDto) {
//查询APP用户信息
const appUserInfo = await ExternalApiService.getAppUserInfo(buyGoodsUserDto.userid, buyGoodsUserDto.token);
if (appUserInfo?.code != 200) return appUserInfo;
const user = appUserInfo.data;
//查询商品信息
const goodsInfo: any = await this.goodsService.findOne(buyGoodsUserDto.goodsid, GoodsStatus.HIDE);
if (goodsInfo?.code != 200) return CustomResult(CODE.CODE_GOODS_INFO_ERR);
const goods = goodsInfo.data;
//判断用户金额是否满足条件 (商品价格*商品数量)
const payCoin = goods.goods_price * buyGoodsUserDto.goods_count;//应支付价格
if (user.coin < payCoin) return CustomResult(CODE.CODE_APPUSER_COIN_NOT_ENOUGHT_ERR);
//TODO 扣减加锁 锁几秒
//用户金额扣减
const subUserInfo = await ExternalApiService.subAppUserCoin(buyGoodsUserDto.userid, buyGoodsUserDto.token, payCoin);
console.log('扣减后用户信息',subUserInfo);
//发放完成记录日志
const orderInfo: CreateOrderlogDto = {
userid: buyGoodsUserDto.userid,
goods_id: goods.goods_id,
goods_type: goods.goods_type,
goods_price: goods.goods_price,
goods_attribute: goods.goods_attribute
}
// const orderRes = await this.orderLogService.create(orderInfo);
// logger.debug(`购买订单日志结果: ${JSON.stringify(orderRes)}`);
// if (orderRes.code != 200) return CustomResult(CODE.CODE_GOODS_DEAL_ERR);
return appUserInfo;
return SuccessResult();
}
}

24
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,24 @@
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!');
});
});

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

15
tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
}