Commit 143c1061 authored by nanahira's avatar nanahira

finish

parent bccff527
Pipeline #11755 canceled with stages
in 3 minutes and 3 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
......@@ -6,7 +6,6 @@
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
......@@ -32,4 +31,8 @@ lerna-debug.log*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
\ No newline at end of file
!.vscode/extensions.json
/data
/output
/config.yaml
\ No newline at end of file
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:
- TARGET_IMAGE=$CONTAINER_TEST_X86_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-arm:
stage: build
tags:
- docker-arm
script:
- TARGET_IMAGE=$CONTAINER_TEST_ARM_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
combine:
stage: combine
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_TEST_IMAGE
- SOURCE_IMAGE_2=$CONTAINER_TEST_ARM_IMAGE
- SOURCE_IMAGE_1=$CONTAINER_TEST_X86_IMAGE
- docker pull $SOURCE_IMAGE_1
- docker pull $SOURCE_IMAGE_2
- docker manifest create $TARGET_IMAGE --amend $SOURCE_IMAGE_1 --amend
$SOURCE_IMAGE_2
- docker manifest push $TARGET_IMAGE
deploy_latest:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_RELEASE_IMAGE
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- master
deploy_tag:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- tags
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
FROM node:bullseye-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential libpq-dev && 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
ENV NODE_PG_FORCE_NATIVE=true
EXPOSE 3000
CMD [ "npm", "run", "start:prod" ]
This diff is collapsed.
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
# rank-provide-bot
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
A bot providing ranks to guild members.
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Environment
## Description
* `DB_HOST` `DB_PORT` `DB_USER` `DB_PASS` `DB_NAME` Database configs.
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
* `ONEBOT_HOST` `ONEBOT_TOKEN` `ONEBOT_ID` OneBot configs.
* `TARGET_GUILDS` A list of guilds to provide ranks to.
## Installation
......@@ -45,29 +29,6 @@ $ npm run start:dev
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
AGPLv3
#!/bin/bash
npm install --save-exact typeorm@0.2.45
npm install --save \
class-validator \
class-transformer \
@nestjs/swagger \
swagger-ui-express \
@nestjs/typeorm \
@nestjs/config \
pg \
pg-native \
reflect-metadata
npm install --save-dev \
@types/express \
@types/multer
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
}
This diff is collapsed.
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();
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.AppModule = void 0;
var common_1 = require("@nestjs/common");
var typeorm_1 = require("@nestjs/typeorm");
var config_1 = require("@nestjs/config");
var koishi_nestjs_1 = require("koishi-nestjs");
var plugin_adapter_onebot_1 = require("@koishijs/plugin-adapter-onebot");
var rank_record_entity_1 = require("./entities/rank-record.entity");
var record_service_1 = require("./record/record.service");
var command_service_1 = require("./command/command.service");
var AppModule = /** @class */ (function () {
function AppModule() {
}
AppModule = __decorate([
(0, common_1.Module)({
imports: [
config_1.ConfigModule.forRoot({
isGlobal: true
}),
typeorm_1.TypeOrmModule.forRootAsync({
inject: [config_1.ConfigService],
useFactory: function (config) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, {
type: 'postgres',
autoLoadEntities: true,
synchronize: !config.get('DB_NO_INIT'),
host: config.get('DB_HOST'),
port: parseInt(config.get('DB_PORT')) || 5432,
username: config.get('DB_USER'),
password: config.get('DB_PASS'),
database: config.get('DB_NAME'),
supportBigNumbers: true,
bigNumberStrings: false
}];
});
}); }
}),
typeorm_1.TypeOrmModule.forFeature([rank_record_entity_1.RankRecord]),
koishi_nestjs_1.KoishiModule.registerAsync({
inject: [config_1.ConfigService],
useFactory: function (config) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, {
minSimilarity: 1,
help: false,
prefix: '.',
usePlugins: [
(0, koishi_nestjs_1.PluginDef)(plugin_adapter_onebot_1["default"], {
bots: [
{
protocol: 'ws',
endpoint: config.get('ONEBOT_HOST'),
token: config.get('ONEBOT_TOKEN'),
selfId: config.get('ONEBOT_ID')
},
]
}),
]
}];
});
}); }
}),
],
providers: [record_service_1.RecordService, command_service_1.CommandService]
})
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { KoishiModule, PluginDef } from 'koishi-nestjs';
import OneBot, { BotConfig } from '@koishijs/plugin-adapter-onebot';
import { RankRecord } from './entities/rank-record.entity';
import { RecordService } from './record/record.service';
import { CommandService } from './command/command.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: async (config: ConfigService) => {
return {
type: 'postgres',
autoLoadEntities: true,
synchronize: !config.get('DB_NO_INIT'),
host: config.get('DB_HOST'),
port: parseInt(config.get('DB_PORT')) || 5432,
username: config.get('DB_USER'),
password: config.get('DB_PASS'),
database: config.get('DB_NAME'),
supportBigNumbers: true,
bigNumberStrings: false,
};
},
}),
TypeOrmModule.forFeature([RankRecord]),
KoishiModule.registerAsync({
inject: [ConfigService],
useFactory: async (config: ConfigService) => {
return {
minSimilarity: 1,
help: false,
prefix: '.',
usePlugins: [
PluginDef(OneBot, {
bots: [
{
protocol: 'ws',
endpoint: config.get('ONEBOT_HOST'),
token: config.get('ONEBOT_TOKEN'),
selfId: config.get('ONEBOT_ID'),
},
] as BotConfig[],
}),
],
};
},
}),
],
providers: [RecordService, CommandService],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.CommandService = void 0;
var common_1 = require("@nestjs/common");
var koishi_nestjs_1 = require("koishi-nestjs");
var CommandService = /** @class */ (function (_super) {
__extends(CommandService, _super);
function CommandService(record) {
var _this = _super.call(this, 'CommandService') || this;
_this.record = record;
return _this;
}
CommandService.prototype.rankCommand = function (session, rank) {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
rank !== null && rank !== void 0 ? rank : (rank = '');
if (rank.length > 6) {
return [2 /*return*/];
}
return [4 /*yield*/, this.record.isCanGiveRecord(session)];
case 1:
if (!(_a.sent())) {
return [2 /*return*/];
}
_a.label = 2;
case 2:
_a.trys.push([2, 5, , 6]);
return [4 /*yield*/, session.bot.internal.setGroupSpecialTitle(session.guildId, session.userId, rank)];
case 3:
_a.sent();
return [4 /*yield*/, this.record.recordGiven(session, rank)];
case 4:
_a.sent();
return [3 /*break*/, 6];
case 5:
e_1 = _a.sent();
this.error("Error when giving rank ".concat(rank, " to ").concat(session.userId, " in ").concat(session.guildId, ": ").concat(e_1.message));
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
};
var _a;
__decorate([
koishi_nestjs_1.OnGuild.apply(void 0, (((_a = process.env.TARGET_GUILDS) === null || _a === void 0 ? void 0 : _a.split(',')) || undefined)),
(0, koishi_nestjs_1.UseCommand)('rank [rank:string]', 'Give a user a rank'),
__param(0, (0, koishi_nestjs_1.PutSession)()),
__param(1, (0, koishi_nestjs_1.PutArg)(0))
], CommandService.prototype, "rankCommand");
CommandService = __decorate([
(0, common_1.Injectable)()
], CommandService);
return CommandService;
}(common_1.ConsoleLogger));
exports.CommandService = CommandService;
import { Test, TestingModule } from '@nestjs/testing';
import { CommandService } from './command.service';
describe('CommandService', () => {
let service: CommandService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CommandService],
}).compile();
service = module.get<CommandService>(CommandService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { ConsoleLogger, Injectable } from '@nestjs/common';
import { OnGuild, PutArg, PutSession, UseCommand } from 'koishi-nestjs';
import { Session } from 'koishi';
import { RecordService } from '../record/record.service';
import { OneBotBot } from '@koishijs/plugin-adapter-onebot';
@Injectable()
export class CommandService extends ConsoleLogger {
constructor(private record: RecordService) {
super('CommandService');
}
@OnGuild(...(process.env.TARGET_GUILDS?.split(',') || []))
@UseCommand('rank [rank:string]', 'Ask for a rank')
async rankCommand(@PutSession() session: Session, @PutArg(0) rank: string) {
rank ??= '';
if (rank.length > 6) {
this.warn(
`Skipped giving rank ${rank} to ${session.userId} because too long: ${rank.length}`,
);
return;
}
if (!(await this.record.isCanGiveRecord(session))) {
this.warn(
`Skipped giving rank ${rank} to ${session.userId} because already given within 2 hours.`,
);
return;
}
this.log(`Giving ${rank} to ${session.userId} in ${session.guildId}`);
try {
await (session.bot as OneBotBot).internal.setGroupSpecialTitle(
session.guildId,
session.userId,
rank,
);
await this.record.recordGiven(session, rank);
this.log(`Given ${rank} to ${session.userId} in ${session.guildId}`);
} catch (e) {
this.error(
`Error when giving rank ${rank} to ${session.userId} in ${session.guildId}: ${e.message}`,
);
}
}
}
This diff is collapsed.
This diff is collapsed.
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
exports.__esModule = true;
exports.CrudFactory = exports.MergeMethodDecorators = void 0;
var swagger_1 = require("@nestjs/swagger");
var common_1 = require("@nestjs/common");
var ReturnMessage_dto_1 = require("../dto/ReturnMessage.dto");
var TimeBase_entity_1 = require("../entities/bases/TimeBase.entity");
var pipes_1 = require("../utility/pipes");
function MergeMethodDecorators(decorators) {
return function (target, key, descriptor) {
decorators.forEach(function (decorator) {
decorator(target, key, descriptor);
});
};
}
exports.MergeMethodDecorators = MergeMethodDecorators;
var CrudFactory = /** @class */ (function () {
function CrudFactory(entityClass, fieldsToOmit,
// eslint-disable-next-line @typescript-eslint/ban-types
idType) {
if (fieldsToOmit === void 0) { fieldsToOmit = []; }
if (idType === void 0) { idType = Number; }
this.entityClass = entityClass;
this.idType = idType;
this.createDto = (0, swagger_1.OmitType)(this.entityClass, __spreadArray(__spreadArray([], TimeBase_entity_1.TimeBaseFields, true), fieldsToOmit, true));
this.updateDto = (0, swagger_1.PartialType)(this.createDto);
this.entityReturnMessageDto = /** @class */ (function (_super) {
__extends(EntityReturnMessageDto, _super);
function EntityReturnMessageDto() {
return _super !== null && _super.apply(this, arguments) || this;
}
return EntityReturnMessageDto;
}((ReturnMessage_dto_1.BlankReturnMessageDto)));
(0, swagger_1.ApiProperty)({ type: this.entityClass })(this.entityReturnMessageDto.prototype, 'data');
this.entityArrayReturnMessageDto = /** @class */ (function (_super) {
__extends(EntityArrayReturnMessageDto, _super);
function EntityArrayReturnMessageDto() {
return _super !== null && _super.apply(this, arguments) || this;
}
return EntityArrayReturnMessageDto;
}((ReturnMessage_dto_1.BlankPaginatedReturnMessageDto)));
(0, swagger_1.ApiProperty)({ type: [this.entityClass] })(this.entityArrayReturnMessageDto.prototype, 'data');
}
CrudFactory.prototype.create = function () {
return MergeMethodDecorators([
(0, common_1.Post)(),
(0, swagger_1.ApiOperation)({ summary: "Create a new ".concat(this.entityClass.name) }),
(0, swagger_1.ApiBody)({ type: this.createDto }),
(0, swagger_1.ApiCreatedResponse)({ type: this.entityReturnMessageDto }),
]);
};
CrudFactory.prototype.createParam = function () {
return (0, common_1.Body)(pipes_1.CreatePipe);
};
CrudFactory.prototype.findOne = function () {
return MergeMethodDecorators([
(0, common_1.Get)(':id'),
(0, swagger_1.ApiOperation)({ summary: "Find a ".concat(this.entityClass.name, " by id") }),
(0, swagger_1.ApiParam)({ name: 'id', type: this.idType, required: true }),
(0, swagger_1.ApiOkResponse)({ type: this.entityReturnMessageDto }),
]);
};
CrudFactory.prototype.findAll = function () {
return MergeMethodDecorators([
(0, common_1.Get)(),
(0, swagger_1.ApiOperation)({ summary: "Find all ".concat(this.entityClass.name) }),
(0, swagger_1.ApiOkResponse)({ type: this.entityArrayReturnMessageDto }),
]);
};
CrudFactory.prototype.findAllParam = function () {
return (0, common_1.Query)(new pipes_1.ClassGetPipe(this.entityClass));
};
CrudFactory.prototype.update = function () {
return MergeMethodDecorators([
(0, common_1.Patch)(':id'),
(0, swagger_1.ApiOperation)({ summary: "Update a ".concat(this.entityClass.name, " by id") }),
(0, swagger_1.ApiParam)({ name: 'id', type: this.idType, required: true }),
(0, swagger_1.ApiBody)({ type: this.updateDto }),
(0, swagger_1.ApiOkResponse)({ type: ReturnMessage_dto_1.BlankReturnMessageDto }),
]);
};
CrudFactory.prototype.updateParam = function () {
return (0, common_1.Body)(pipes_1.UpdatePipe);
};
CrudFactory.prototype["delete"] = function () {
return MergeMethodDecorators([
(0, common_1.Delete)(':id'),
(0, swagger_1.ApiOperation)({ summary: "Delete a ".concat(this.entityClass.name, " by id") }),
(0, swagger_1.ApiParam)({ name: 'id', type: this.idType, required: true }),
(0, swagger_1.ApiNoContentResponse)({ type: ReturnMessage_dto_1.BlankReturnMessageDto }),
]);
};
return CrudFactory;
}());
exports.CrudFactory = CrudFactory;
import {
ApiBody,
ApiCreatedResponse,
ApiNoContentResponse,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiProperty,
OmitType,
PartialType,
} from '@nestjs/swagger';
import { Body, Delete, Get, Patch, Post, Query, Type } from '@nestjs/common';
import {
BlankPaginatedReturnMessageDto,
BlankReturnMessageDto,
PaginatedReturnMessageDto,
ReturnMessageDto,
} from '../dto/ReturnMessage.dto';
import { TimeBase, TimeBaseFields } from '../entities/bases/TimeBase.entity';
import { ClassGetPipe, CreatePipe, UpdatePipe } from '../utility/pipes';
export function MergeMethodDecorators(
decorators: MethodDecorator[],
): MethodDecorator {
return (target: any, key: string, descriptor: PropertyDescriptor) => {
decorators.forEach((decorator) => {
decorator(target, key, descriptor);
});
};
}
export class CrudFactory<T extends TimeBase> {
readonly createDto: Type<Omit<T, keyof T>>;
readonly updateDto: Type<Partial<Omit<T, keyof T>>>;
readonly entityReturnMessageDto: Type<ReturnMessageDto<T>>;
readonly entityArrayReturnMessageDto: Type<PaginatedReturnMessageDto<T>>;
constructor(
public readonly entityClass: Type<T>,
fieldsToOmit: (keyof T)[] = [],
// eslint-disable-next-line @typescript-eslint/ban-types
public readonly idType: Function = Number,
) {
this.createDto = OmitType(this.entityClass, [
...TimeBaseFields,
...fieldsToOmit,
]);
this.updateDto = PartialType(this.createDto);
this.entityReturnMessageDto = class EntityReturnMessageDto extends (
BlankReturnMessageDto
) {
data: T;
};
ApiProperty({ type: this.entityClass })(
this.entityReturnMessageDto.prototype,
'data',
);
this.entityArrayReturnMessageDto = class EntityArrayReturnMessageDto extends (
BlankPaginatedReturnMessageDto
) {
data: T[];
};
ApiProperty({ type: [this.entityClass] })(
this.entityArrayReturnMessageDto.prototype,
'data',
);
}
create(): MethodDecorator {
return MergeMethodDecorators([
Post(),
ApiOperation({ summary: `Create a new ${this.entityClass.name}` }),
ApiBody({ type: this.createDto }),
ApiCreatedResponse({ type: this.entityReturnMessageDto }),
]);
}
createParam() {
return Body(CreatePipe);
}
findOne(): MethodDecorator {
return MergeMethodDecorators([
Get(':id'),
ApiOperation({ summary: `Find a ${this.entityClass.name} by id` }),
ApiParam({ name: 'id', type: this.idType, required: true }),
ApiOkResponse({ type: this.entityReturnMessageDto }),
]);
}
findAll(): MethodDecorator {
return MergeMethodDecorators([
Get(),
ApiOperation({ summary: `Find all ${this.entityClass.name}` }),
ApiOkResponse({ type: this.entityArrayReturnMessageDto }),
]);
}
findAllParam() {
return Query(new ClassGetPipe(this.entityClass));
}
update(): MethodDecorator {
return MergeMethodDecorators([
Patch(':id'),
ApiOperation({ summary: `Update a ${this.entityClass.name} by id` }),
ApiParam({ name: 'id', type: this.idType, required: true }),
ApiBody({ type: this.updateDto }),
ApiOkResponse({ type: BlankReturnMessageDto }),
]);
}
updateParam() {
return Body(UpdatePipe);
}
delete(): MethodDecorator {
return MergeMethodDecorators([
Delete(':id'),
ApiOperation({ summary: `Delete a ${this.entityClass.name} by id` }),
ApiParam({ name: 'id', type: this.idType, required: true }),
ApiNoContentResponse({ type: BlankReturnMessageDto }),
]);
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.PageSettingsDto = void 0;
var openapi = require("@nestjs/swagger");
var class_validator_1 = require("class-validator");
var swagger_1 = require("@nestjs/swagger");
var transform_1 = require("../entities/decorators/transform");
var PageSettingsDto = /** @class */ (function () {
function PageSettingsDto() {
}
PageSettingsDto.prototype.getActualPageSettings = function () {
return {
pageCount: this.getPageCount(),
recordsPerPage: this.getRecordsPerPage()
};
};
PageSettingsDto.prototype.getPageCount = function () {
return this.pageCount || 1;
};
PageSettingsDto.prototype.getRecordsPerPage = function () {
return this.recordsPerPage || 25;
};
PageSettingsDto.prototype.getStartingFrom = function () {
return (this.getPageCount() - 1) * this.getRecordsPerPage();
};
PageSettingsDto.prototype.applyQuery = function (qb, entityName) {
qb.take(this.getRecordsPerPage()).skip(this.getStartingFrom());
};
PageSettingsDto._OPENAPI_METADATA_FACTORY = function () {
return { pageCount: { required: true, type: function () { return Number; }, minimum: 1 }, recordsPerPage: { required: true, type: function () { return Number; }, minimum: 1 } };
};
__decorate([
(0, transform_1.NotWritable)(),
(0, class_validator_1.IsPositive)(),
(0, class_validator_1.IsInt)(),
(0, swagger_1.ApiProperty)({ description: '第 n 页,从 1 开始', required: false })
], PageSettingsDto.prototype, "pageCount");
__decorate([
(0, transform_1.NotWritable)(),
(0, class_validator_1.IsPositive)(),
(0, class_validator_1.IsInt)(),
(0, swagger_1.ApiProperty)({ description: '每页显示的数量', required: false })
], PageSettingsDto.prototype, "recordsPerPage");
return PageSettingsDto;
}());
exports.PageSettingsDto = PageSettingsDto;
import { IsInt, IsPositive } from 'class-validator';
import { SelectQueryBuilder } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { NotWritable } from '../entities/decorators/transform';
export interface PageSettingsWise {
pageCount: number;
recordsPerPage: number;
}
export interface PageSettingsFactory {
getActualPageSettings(): PageSettingsWise;
}
export class PageSettingsDto implements PageSettingsWise, PageSettingsFactory {
@NotWritable()
@IsPositive()
@IsInt()
@ApiProperty({ description: '第 n 页,从 1 开始', required: false })
pageCount: number;
@NotWritable()
@IsPositive()
@IsInt()
@ApiProperty({ description: '每页显示的数量', required: false })
recordsPerPage: number;
getActualPageSettings(): PageSettingsWise {
return {
pageCount: this.getPageCount(),
recordsPerPage: this.getRecordsPerPage(),
};
}
private getPageCount() {
return this.pageCount || 1;
}
private getRecordsPerPage() {
return this.recordsPerPage || 25;
}
private getStartingFrom() {
return (this.getPageCount() - 1) * this.getRecordsPerPage();
}
applyQuery(qb: SelectQueryBuilder<PageSettingsDto>, entityName: string) {
qb.take(this.getRecordsPerPage()).skip(this.getStartingFrom());
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.StringReturnMessageDto = exports.PaginatedReturnMessageDto = exports.ReturnMessageDto = exports.BlankPaginatedReturnMessageDto = exports.BlankReturnMessageDto = void 0;
var openapi = require("@nestjs/swagger");
var swagger_1 = require("@nestjs/swagger");
var common_1 = require("@nestjs/common");
var BlankReturnMessageDto = /** @class */ (function () {
function BlankReturnMessageDto(statusCode, message) {
this.statusCode = statusCode;
this.message = message || 'success';
this.success = statusCode < 400;
}
BlankReturnMessageDto.prototype.toException = function () {
return new common_1.HttpException(this, this.statusCode);
};
BlankReturnMessageDto._OPENAPI_METADATA_FACTORY = function () {
return { statusCode: { required: true, type: function () { return Number; } }, message: { required: true, type: function () { return String; } }, success: { required: true, type: function () { return Boolean; } } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '返回状态' })
], BlankReturnMessageDto.prototype, "statusCode");
__decorate([
(0, swagger_1.ApiProperty)({ description: '返回信息' })
], BlankReturnMessageDto.prototype, "message");
__decorate([
(0, swagger_1.ApiProperty)({ description: '是否成功' })
], BlankReturnMessageDto.prototype, "success");
return BlankReturnMessageDto;
}());
exports.BlankReturnMessageDto = BlankReturnMessageDto;
var BlankPaginatedReturnMessageDto = /** @class */ (function (_super) {
__extends(BlankPaginatedReturnMessageDto, _super);
function BlankPaginatedReturnMessageDto(statusCode, message, total, pageSettings) {
var _this = _super.call(this, statusCode, message) || this;
_this.total = total;
_this.pageCount = pageSettings.pageCount;
_this.recordsPerPage = pageSettings.recordsPerPage;
_this.totalPages = Math.ceil(total / pageSettings.recordsPerPage);
return _this;
}
BlankPaginatedReturnMessageDto._OPENAPI_METADATA_FACTORY = function () {
return { total: { required: true, type: function () { return Number; } }, totalPages: { required: true, type: function () { return Number; } }, pageCount: { required: true, type: function () { return Number; } }, recordsPerPage: { required: true, type: function () { return Number; } } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '总数' })
], BlankPaginatedReturnMessageDto.prototype, "total");
__decorate([
(0, swagger_1.ApiProperty)({ description: '总页数' })
], BlankPaginatedReturnMessageDto.prototype, "totalPages");
__decorate([
(0, swagger_1.ApiProperty)({ description: '当前页' })
], BlankPaginatedReturnMessageDto.prototype, "pageCount");
__decorate([
(0, swagger_1.ApiProperty)({ description: '每页数量' })
], BlankPaginatedReturnMessageDto.prototype, "recordsPerPage");
return BlankPaginatedReturnMessageDto;
}(BlankReturnMessageDto));
exports.BlankPaginatedReturnMessageDto = BlankPaginatedReturnMessageDto;
var ReturnMessageDto = /** @class */ (function (_super) {
__extends(ReturnMessageDto, _super);
function ReturnMessageDto(statusCode, message, data) {
var _this = _super.call(this, statusCode, message) || this;
_this.data = data;
return _this;
}
ReturnMessageDto._OPENAPI_METADATA_FACTORY = function () {
return { data: { required: false } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '返回内容' })
], ReturnMessageDto.prototype, "data");
return ReturnMessageDto;
}(BlankReturnMessageDto));
exports.ReturnMessageDto = ReturnMessageDto;
var PaginatedReturnMessageDto = /** @class */ (function (_super) {
__extends(PaginatedReturnMessageDto, _super);
function PaginatedReturnMessageDto(statusCode, message, data, total, pageSettings) {
var _this = _super.call(this, statusCode, message, total, pageSettings) || this;
_this.data = data;
return _this;
}
PaginatedReturnMessageDto._OPENAPI_METADATA_FACTORY = function () {
return { data: { required: true } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '返回内容' })
], PaginatedReturnMessageDto.prototype, "data");
return PaginatedReturnMessageDto;
}(BlankPaginatedReturnMessageDto));
exports.PaginatedReturnMessageDto = PaginatedReturnMessageDto;
var StringReturnMessageDto = /** @class */ (function (_super) {
__extends(StringReturnMessageDto, _super);
function StringReturnMessageDto() {
return _super !== null && _super.apply(this, arguments) || this;
}
StringReturnMessageDto._OPENAPI_METADATA_FACTORY = function () {
return { data: { required: false, type: function () { return String; } } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '返回内容' })
], StringReturnMessageDto.prototype, "data");
return StringReturnMessageDto;
}(BlankReturnMessageDto));
exports.StringReturnMessageDto = StringReturnMessageDto;
import { ApiProperty } from '@nestjs/swagger';
import { HttpException } from '@nestjs/common';
import { PageSettingsWise } from './PageSettings.dto';
export interface BlankReturnMessage {
statusCode: number;
message: string;
success: boolean;
}
export interface ReturnMessage<T> extends BlankReturnMessage {
data?: T;
}
export class BlankReturnMessageDto implements BlankReturnMessage {
@ApiProperty({ description: '返回状态' })
statusCode: number;
@ApiProperty({ description: '返回信息' })
message: string;
@ApiProperty({ description: '是否成功' })
success: boolean;
constructor(statusCode: number, message?: string) {
this.statusCode = statusCode;
this.message = message || 'success';
this.success = statusCode < 400;
}
toException() {
return new HttpException(this, this.statusCode);
}
}
export class BlankPaginatedReturnMessageDto
extends BlankReturnMessageDto
implements PageSettingsWise {
@ApiProperty({ description: '总数' })
total: number;
@ApiProperty({ description: '总页数' })
totalPages: number;
@ApiProperty({ description: '当前页' })
pageCount: number;
@ApiProperty({ description: '每页数量' })
recordsPerPage: number;
constructor(
statusCode: number,
message: string,
total: number,
pageSettings: PageSettingsWise,
) {
super(statusCode, message);
this.total = total;
this.pageCount = pageSettings.pageCount;
this.recordsPerPage = pageSettings.recordsPerPage;
this.totalPages = Math.ceil(total / pageSettings.recordsPerPage);
}
}
export class ReturnMessageDto<T>
extends BlankReturnMessageDto
implements ReturnMessage<T> {
@ApiProperty({ description: '返回内容' })
data?: T;
constructor(statusCode: number, message?: string, data?: T) {
super(statusCode, message);
this.data = data;
}
}
export class PaginatedReturnMessageDto<T>
extends BlankPaginatedReturnMessageDto
implements PageSettingsWise {
@ApiProperty({ description: '返回内容' })
data: T[];
constructor(
statusCode: number,
message: string,
data: T[],
total: number,
pageSettings: PageSettingsWise,
) {
super(statusCode, message, total, pageSettings);
this.data = data;
}
}
export class StringReturnMessageDto
extends BlankReturnMessageDto
implements ReturnMessage<string> {
@ApiProperty({ description: '返回内容' })
data?: string;
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.ImportEntryBaseDto = void 0;
var openapi = require("@nestjs/swagger");
var swagger_1 = require("@nestjs/swagger");
var ImportEntryBaseDto = /** @class */ (function () {
function ImportEntryBaseDto() {
}
ImportEntryBaseDto._OPENAPI_METADATA_FACTORY = function () {
return { result: { required: true, type: function () { return String; } } };
};
__decorate([
(0, swagger_1.ApiProperty)({ description: '导入结果' })
], ImportEntryBaseDto.prototype, "result");
return ImportEntryBaseDto;
}());
exports.ImportEntryBaseDto = ImportEntryBaseDto;
import { ApiProperty } from '@nestjs/swagger';
export class ImportEntryBaseDto {
@ApiProperty({ description: '导入结果' })
result: string;
}
export interface ImportEntry<T> {
entry: T;
result: string;
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.AvatarBase = void 0;
var openapi = require("@nestjs/swagger");
var IdNameDescBase_entity_1 = require("./IdNameDescBase.entity");
var base_1 = require("../decorators/base");
var query_1 = require("../utility/query");
var AvatarBase = /** @class */ (function (_super) {
__extends(AvatarBase, _super);
function AvatarBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
AvatarBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryPropertyLike)(this, qb, entityName, 'avatarUrl');
};
AvatarBase._OPENAPI_METADATA_FACTORY = function () {
return { avatarUrl: { required: true, type: function () { return String; } } };
};
__decorate([
(0, base_1.StringColumn)(128, '图标地址', undefined, false)
], AvatarBase.prototype, "avatarUrl");
return AvatarBase;
}(IdNameDescBase_entity_1.IdNameDescBase));
exports.AvatarBase = AvatarBase;
import { IdNameDescBase } from './IdNameDescBase.entity';
import { StringColumn } from '../decorators/base';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryPropertyLike } from '../utility/query';
export class AvatarBase extends IdNameDescBase {
@StringColumn(128, '图标地址', undefined, false)
avatarUrl: string;
override applyQuery(qb: SelectQueryBuilder<AvatarBase>, entityName: string) {
super.applyQuery(qb, entityName);
applyQueryPropertyLike(this, qb, entityName, 'avatarUrl');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.IdBase = void 0;
var openapi = require("@nestjs/swagger");
var typeorm_1 = require("typeorm");
var swagger_1 = require("@nestjs/swagger");
var query_1 = require("../utility/query");
var transform_1 = require("../decorators/transform");
var class_validator_1 = require("class-validator");
var bigint_transform_1 = require("../utility/bigint-transform");
var TimeBase_entity_1 = require("./TimeBase.entity");
var IdBase = /** @class */ (function (_super) {
__extends(IdBase, _super);
function IdBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
IdBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
qb.orderBy("".concat(entityName, ".id"), 'DESC');
(0, query_1.applyQueryProperty)(this, qb, entityName, 'id');
};
IdBase._OPENAPI_METADATA_FACTORY = function () {
return { id: { required: true, type: function () { return Number; }, minimum: 1 } };
};
__decorate([
(0, typeorm_1.Generated)('increment'),
(0, typeorm_1.Column)('bigint', {
primary: true,
unsigned: true,
transformer: new bigint_transform_1.BigintTransformer()
}),
(0, swagger_1.ApiProperty)({ description: '编号', required: false }),
(0, transform_1.NotWritable)(),
(0, class_validator_1.IsInt)(),
(0, class_validator_1.IsPositive)()
], IdBase.prototype, "id");
return IdBase;
}(TimeBase_entity_1.TimeBase));
exports.IdBase = IdBase;
import { Column, Generated, SelectQueryBuilder } from 'typeorm';
import { IdWise } from '../interfaces/wises';
import { ApiProperty } from '@nestjs/swagger';
import { applyQueryProperty } from '../utility/query';
import { NotWritable } from '../decorators/transform';
import { IsInt, IsPositive } from 'class-validator';
import { BigintTransformer } from '../utility/bigint-transform';
import { TimeBase } from './TimeBase.entity';
export class IdBase extends TimeBase implements IdWise {
@Generated('increment')
@Column('bigint', {
primary: true,
unsigned: true,
transformer: new BigintTransformer(),
})
@ApiProperty({ description: '编号', required: false })
@NotWritable()
@IsInt()
@IsPositive()
id: number;
override applyQuery(qb: SelectQueryBuilder<IdBase>, entityName: string) {
super.applyQuery(qb, entityName);
qb.orderBy(`${entityName}.id`, 'DESC');
applyQueryProperty(this, qb, entityName, 'id');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.IdNameBase = void 0;
var openapi = require("@nestjs/swagger");
var IdBase_entity_1 = require("./IdBase.entity");
var extended_1 = require("../decorators/extended");
var query_1 = require("../utility/query");
var IdNameBase = /** @class */ (function (_super) {
__extends(IdNameBase, _super);
function IdNameBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
IdNameBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryPropertyLike)(this, qb, entityName, 'name');
};
IdNameBase._OPENAPI_METADATA_FACTORY = function () {
return { name: { required: true, type: function () { return String; } } };
};
__decorate([
(0, extended_1.EntityName)()
], IdNameBase.prototype, "name");
return IdNameBase;
}(IdBase_entity_1.IdBase));
exports.IdNameBase = IdNameBase;
import { IdBase } from './IdBase.entity';
import { IdNameWise } from '../interfaces/wises';
import { EntityName } from '../decorators/extended';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryPropertyLike } from '../utility/query';
export class IdNameBase extends IdBase implements IdNameWise {
@EntityName()
name: string;
override applyQuery(qb: SelectQueryBuilder<IdNameBase>, entityName: string) {
super.applyQuery(qb, entityName);
applyQueryPropertyLike(this, qb, entityName, 'name');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.IdNameDescBase = void 0;
var openapi = require("@nestjs/swagger");
var IdNameBase_entity_1 = require("./IdNameBase.entity");
var extended_1 = require("../decorators/extended");
var query_1 = require("../utility/query");
var IdNameDescBase = /** @class */ (function (_super) {
__extends(IdNameDescBase, _super);
function IdNameDescBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
IdNameDescBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryPropertySearch)(this, qb, entityName, 'desc');
};
IdNameDescBase._OPENAPI_METADATA_FACTORY = function () {
return { desc: { required: true, type: function () { return String; } } };
};
__decorate([
(0, extended_1.EntityDescription)()
], IdNameDescBase.prototype, "desc");
return IdNameDescBase;
}(IdNameBase_entity_1.IdNameBase));
exports.IdNameDescBase = IdNameDescBase;
import { IdNameBase } from './IdNameBase.entity';
import { IdNameDescWise } from '../interfaces/wises';
import { EntityDescription } from '../decorators/extended';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryPropertySearch } from '../utility/query';
export class IdNameDescBase extends IdNameBase implements IdNameDescWise {
@EntityDescription()
desc: string;
override applyQuery(
qb: SelectQueryBuilder<IdNameDescBase>,
entityName: string,
) {
super.applyQuery(qb, entityName);
applyQueryPropertySearch(this, qb, entityName, 'desc');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.AvatarBase = void 0;
var openapi = require("@nestjs/swagger");
var base_1 = require("../decorators/base");
var query_1 = require("../utility/query");
var ManualNameDescBase_entity_1 = require("./ManualNameDescBase.entity");
var AvatarBase = /** @class */ (function (_super) {
__extends(AvatarBase, _super);
function AvatarBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
AvatarBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryProperty)(this, qb, entityName, 'avatarUrl');
};
AvatarBase._OPENAPI_METADATA_FACTORY = function () {
return { avatarUrl: { required: true, type: function () { return String; } } };
};
__decorate([
(0, base_1.StringColumn)(128, '图标地址', undefined, false)
], AvatarBase.prototype, "avatarUrl");
return AvatarBase;
}(ManualNameDescBase_entity_1.ManualNameDescBase));
exports.AvatarBase = AvatarBase;
import { StringColumn } from '../decorators/base';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryProperty } from '../utility/query';
import { ManualNameDescBase } from './ManualNameDescBase.entity';
export class AvatarBase extends ManualNameDescBase {
@StringColumn(128, '图标地址', undefined, false)
avatarUrl: string;
override applyQuery(qb: SelectQueryBuilder<AvatarBase>, entityName: string) {
super.applyQuery(qb, entityName);
applyQueryProperty(this, qb, entityName, 'avatarUrl');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.ManualIdBase = void 0;
var openapi = require("@nestjs/swagger");
var typeorm_1 = require("typeorm");
var swagger_1 = require("@nestjs/swagger");
var query_1 = require("../utility/query");
var transform_1 = require("../decorators/transform");
var class_validator_1 = require("class-validator");
var TimeBase_entity_1 = require("./TimeBase.entity");
var ManualIdBase = /** @class */ (function (_super) {
__extends(ManualIdBase, _super);
function ManualIdBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
ManualIdBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
qb.orderBy("".concat(entityName, ".id"), 'ASC');
(0, query_1.applyQueryProperty)(this, qb, entityName, 'id');
};
ManualIdBase._OPENAPI_METADATA_FACTORY = function () {
return { id: { required: true, type: function () { return String; } } };
};
__decorate([
(0, typeorm_1.PrimaryColumn)('varchar', { length: 32 }),
(0, swagger_1.ApiProperty)({ description: '编号' }),
(0, transform_1.NotChangeable)(),
(0, class_validator_1.IsString)(),
(0, class_validator_1.IsNotEmpty)()
], ManualIdBase.prototype, "id");
return ManualIdBase;
}(TimeBase_entity_1.TimeBase));
exports.ManualIdBase = ManualIdBase;
import { PrimaryColumn, SelectQueryBuilder } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { StringIdWise } from '../interfaces/wises';
import { applyQueryProperty } from '../utility/query';
import { NotChangeable } from '../decorators/transform';
import { IsNotEmpty, IsString } from 'class-validator';
import { TimeBase } from './TimeBase.entity';
export class ManualIdBase extends TimeBase implements StringIdWise {
@PrimaryColumn('varchar', { length: 32 })
@ApiProperty({ description: '编号' })
@NotChangeable()
@IsString()
@IsNotEmpty()
id: string;
override applyQuery(
qb: SelectQueryBuilder<ManualIdBase>,
entityName: string,
) {
super.applyQuery(qb, entityName);
qb.orderBy(`${entityName}.id`, 'ASC');
applyQueryProperty(this, qb, entityName, 'id');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.ManualNameBase = void 0;
var openapi = require("@nestjs/swagger");
var ManualIdBase_entity_1 = require("./ManualIdBase.entity");
var extended_1 = require("../decorators/extended");
var query_1 = require("../utility/query");
var ManualNameBase = /** @class */ (function (_super) {
__extends(ManualNameBase, _super);
function ManualNameBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
ManualNameBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryPropertyLike)(this, qb, entityName, 'name');
};
ManualNameBase._OPENAPI_METADATA_FACTORY = function () {
return { name: { required: true, type: function () { return String; } } };
};
__decorate([
(0, extended_1.EntityName)()
], ManualNameBase.prototype, "name");
return ManualNameBase;
}(ManualIdBase_entity_1.ManualIdBase));
exports.ManualNameBase = ManualNameBase;
import { ManualIdBase } from './ManualIdBase.entity';
import { StringIdNameWise } from '../interfaces/wises';
import { EntityName } from '../decorators/extended';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryPropertyLike } from '../utility/query';
export class ManualNameBase extends ManualIdBase implements StringIdNameWise {
@EntityName()
name: string;
override applyQuery(
qb: SelectQueryBuilder<ManualNameBase>,
entityName: string,
) {
super.applyQuery(qb, entityName);
applyQueryPropertyLike(this, qb, entityName, 'name');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.ManualNameDescBase = void 0;
var openapi = require("@nestjs/swagger");
var ManualNameBase_entity_1 = require("./ManualNameBase.entity");
var extended_1 = require("../decorators/extended");
var query_1 = require("../utility/query");
var ManualNameDescBase = /** @class */ (function (_super) {
__extends(ManualNameDescBase, _super);
function ManualNameDescBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
ManualNameDescBase.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryPropertySearch)(this, qb, entityName, 'desc');
};
ManualNameDescBase._OPENAPI_METADATA_FACTORY = function () {
return { desc: { required: true, type: function () { return String; } } };
};
__decorate([
(0, extended_1.EntityDescription)()
], ManualNameDescBase.prototype, "desc");
return ManualNameDescBase;
}(ManualNameBase_entity_1.ManualNameBase));
exports.ManualNameDescBase = ManualNameDescBase;
import { ManualNameBase } from './ManualNameBase.entity';
import { StringIdNameDescWise } from '../interfaces/wises';
import { EntityDescription } from '../decorators/extended';
import { SelectQueryBuilder } from 'typeorm';
import { applyQueryPropertySearch } from '../utility/query';
export class ManualNameDescBase
extends ManualNameBase
implements StringIdNameDescWise
{
@EntityDescription()
desc: string;
override applyQuery(
qb: SelectQueryBuilder<ManualNameDescBase>,
entityName: string,
) {
super.applyQuery(qb, entityName);
applyQueryPropertySearch(this, qb, entityName, 'desc');
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.TimeBaseFields = exports.TimeBase = void 0;
var openapi = require("@nestjs/swagger");
var typeorm_1 = require("typeorm");
var PageSettings_dto_1 = require("../../dto/PageSettings.dto");
var base_1 = require("../decorators/base");
var TimeBase = /** @class */ (function (_super) {
__extends(TimeBase, _super);
function TimeBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
TimeBase.prototype.toObject = function () {
return JSON.parse(JSON.stringify(this));
};
TimeBase.prototype.isValidInCreation = function () {
return;
};
TimeBase.prototype.prepareForSaving = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
};
TimeBase.prototype.afterSaving = function () { };
TimeBase._OPENAPI_METADATA_FACTORY = function () {
return { createTime: { required: true, type: function () { return Date; } }, updateTime: { required: true, type: function () { return Date; } }, deleteTime: { required: true, type: function () { return Date; } } };
};
__decorate([
(0, typeorm_1.CreateDateColumn)({ select: false }),
(0, base_1.NotColumn)()
], TimeBase.prototype, "createTime");
__decorate([
(0, typeorm_1.UpdateDateColumn)({ select: false }),
(0, base_1.NotColumn)()
], TimeBase.prototype, "updateTime");
__decorate([
(0, typeorm_1.DeleteDateColumn)({ select: false }),
(0, base_1.NotColumn)()
], TimeBase.prototype, "deleteTime");
return TimeBase;
}(PageSettings_dto_1.PageSettingsDto));
exports.TimeBase = TimeBase;
exports.TimeBaseFields = [
'createTime',
'updateTime',
'deleteTime',
];
import { CreateDateColumn, DeleteDateColumn, UpdateDateColumn } from 'typeorm';
import { PageSettingsDto } from '../../dto/PageSettings.dto';
import { NotColumn } from '../decorators/base';
export interface DeletionWise {
deleteTime?: Date;
}
export interface ImportWise {
isValidInCreation(): string | undefined;
prepareForSaving(): Promise<void>;
afterSaving(): void;
}
export class TimeBase
extends PageSettingsDto
implements DeletionWise, ImportWise
{
@CreateDateColumn({ select: false })
@NotColumn()
createTime: Date;
@UpdateDateColumn({ select: false })
@NotColumn()
updateTime: Date;
@DeleteDateColumn({ select: false })
@NotColumn()
deleteTime: Date;
toObject() {
return JSON.parse(JSON.stringify(this));
}
isValidInCreation(): string | undefined {
return;
}
async prepareForSaving(): Promise<void> {}
afterSaving() {}
}
export const TimeBaseFields: (keyof TimeBase)[] = [
'createTime',
'updateTime',
'deleteTime',
];
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
exports.__esModule = true;
exports.NotColumn = exports.EnumColumn = exports.IntColumn = exports.StringColumn = exports.OptionalValidate = exports.MergePropertyDecorators = void 0;
var typeorm_1 = require("typeorm");
var swagger_1 = require("@nestjs/swagger");
var class_validator_1 = require("class-validator");
var bigint_transform_1 = require("../utility/bigint-transform");
var class_transformer_1 = require("class-transformer");
function MergePropertyDecorators(decs) {
return function (obj, key) {
for (var _i = 0, decs_1 = decs; _i < decs_1.length; _i++) {
var dec = decs_1[_i];
dec(obj, key);
}
};
}
exports.MergePropertyDecorators = MergePropertyDecorators;
var OptionalValidate = function () {
var conitions = [];
for (var _i = 0; _i < arguments.length; _i++) {
conitions[_i] = arguments[_i];
}
return MergePropertyDecorators(__spreadArray([(0, class_validator_1.IsOptional)()], conitions, true));
};
exports.OptionalValidate = OptionalValidate;
var StringColumn = function (length, description, defaultValue, required, columnExtras, propertyExtras) {
if (length === void 0) { length = 32; }
if (description === void 0) { description = 'unknown'; }
if (required === void 0) { required = false; }
if (columnExtras === void 0) { columnExtras = {}; }
if (propertyExtras === void 0) { propertyExtras = {}; }
return MergePropertyDecorators(__spreadArray(__spreadArray([
(0, typeorm_1.Column)('varchar', __assign({ length: length, "default": defaultValue, nullable: !required && defaultValue == null, comment: description }, columnExtras)),
(0, swagger_1.ApiProperty)(__assign({ type: String, description: description, "default": defaultValue, required: required && defaultValue == null, maxLength: length }, propertyExtras))
], (required ? [] : [(0, class_validator_1.IsOptional)()]), true), [
(0, class_validator_1.IsString)(),
(0, class_validator_1.IsNotEmpty)(),
(0, class_validator_1.MaxLength)(length),
], false));
};
exports.StringColumn = StringColumn;
var IntColumn = function (type, unsigned, description, defaultValue, required, columnExtras, propertyExtras) {
if (type === void 0) { type = 'int'; }
if (unsigned === void 0) { unsigned = false; }
if (description === void 0) { description = 'unknown'; }
if (required === void 0) { required = false; }
if (columnExtras === void 0) { columnExtras = {}; }
if (propertyExtras === void 0) { propertyExtras = {}; }
return MergePropertyDecorators(__spreadArray(__spreadArray(__spreadArray([
(0, typeorm_1.Column)(type, __assign(__assign({ "default": defaultValue, nullable: !required && defaultValue == null, unsigned: unsigned, comment: description }, (type === 'bigint' ? { transformer: new bigint_transform_1.BigintTransformer() } : {})), columnExtras)),
(0, swagger_1.ApiProperty)(__assign({ type: Number, description: description, "default": defaultValue, required: required && defaultValue == null }, propertyExtras))
], (required ? [] : [(0, class_validator_1.IsOptional)()]), true), [
(0, class_validator_1.IsInt)()
], false), (unsigned ? [(0, class_validator_1.Min)(0)] : []), true));
};
exports.IntColumn = IntColumn;
var EnumColumn = function (targetEnum, description, defaultValue, required, columnExtras, swaggerExtras) {
if (description === void 0) { description = 'unknown'; }
if (required === void 0) { required = false; }
if (columnExtras === void 0) { columnExtras = {}; }
if (swaggerExtras === void 0) { swaggerExtras = {}; }
return MergePropertyDecorators(__spreadArray(__spreadArray([
(0, typeorm_1.Index)(),
(0, typeorm_1.Column)('enum', __assign({ "enum": targetEnum, "default": defaultValue, nullable: !required && !defaultValue, comment: description }, columnExtras)),
(0, swagger_1.ApiProperty)(__assign({ description: description, "enum": targetEnum, "default": defaultValue, required: required }, swaggerExtras))
], (required ? [] : [(0, class_validator_1.IsOptional)()]), true), [
(0, class_validator_1.IsEnum)(targetEnum),
], false));
};
exports.EnumColumn = EnumColumn;
var NotColumn = function (description, swaggerExtras) {
if (swaggerExtras === void 0) { swaggerExtras = {}; }
return MergePropertyDecorators([
(0, class_transformer_1.Exclude)(),
(0, swagger_1.ApiProperty)(__assign({ description: description, required: false, readOnly: true }, swaggerExtras)),
]);
};
exports.NotColumn = NotColumn;
import { Column, Index } from 'typeorm';
import { ApiProperty, ApiPropertyOptions } from '@nestjs/swagger';
import { ColumnWithLengthOptions } from 'typeorm/decorator/options/ColumnWithLengthOptions';
import { ColumnCommonOptions } from 'typeorm/decorator/options/ColumnCommonOptions';
import { ColumnEnumOptions } from 'typeorm/decorator/options/ColumnEnumOptions';
import {
IsEnum,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
Min,
} from 'class-validator';
import { ColumnWithWidthOptions } from 'typeorm/decorator/options/ColumnWithWidthOptions';
import { BigintTransformer } from '../utility/bigint-transform';
import { Exclude } from 'class-transformer';
export function MergePropertyDecorators(
decs: PropertyDecorator[],
): PropertyDecorator {
return (obj, key) => {
for (const dec of decs) {
dec(obj, key);
}
};
}
export const OptionalValidate = (...conitions: PropertyDecorator[]) =>
MergePropertyDecorators([IsOptional(), ...conitions]);
export const StringColumn = (
length = 32,
description = 'unknown',
defaultValue?: string,
required = false,
columnExtras: ColumnCommonOptions & ColumnWithLengthOptions = {},
propertyExtras: ApiPropertyOptions = {},
) =>
MergePropertyDecorators([
Column('varchar', {
length,
default: defaultValue,
nullable: !required && defaultValue == null,
comment: description,
...columnExtras,
}),
ApiProperty({
type: String,
description,
default: defaultValue,
required: required && defaultValue == null,
maxLength: length,
...propertyExtras,
}),
...(required ? [] : [IsOptional()]),
IsString(),
IsNotEmpty(),
MaxLength(length),
]);
export const IntColumn = (
type: 'int' | 'smallint' | 'bigint' | 'tinyint' = 'int',
unsigned = false,
description = 'unknown',
defaultValue?: number,
required = false,
columnExtras: ColumnCommonOptions & ColumnWithWidthOptions = {},
propertyExtras: ApiPropertyOptions = {},
) =>
MergePropertyDecorators([
Column(type, {
default: defaultValue,
nullable: !required && defaultValue == null,
unsigned,
comment: description,
...(type === 'bigint' ? { transformer: new BigintTransformer() } : {}),
...columnExtras,
}),
ApiProperty({
type: Number,
description,
default: defaultValue,
required: required && defaultValue == null,
...propertyExtras,
}),
...(required ? [] : [IsOptional()]),
IsInt(),
...(unsigned ? [Min(0)] : []),
]);
export const EnumColumn = <T>(
targetEnum: Record<string, T>,
description = 'unknown',
defaultValue?: T,
required = false,
columnExtras: ColumnCommonOptions & ColumnEnumOptions = {},
swaggerExtras: ApiPropertyOptions = {},
) =>
MergePropertyDecorators([
Index(),
Column('enum', {
enum: targetEnum,
default: defaultValue,
nullable: !required && !defaultValue,
comment: description,
...columnExtras,
}),
ApiProperty({
description,
enum: targetEnum,
default: defaultValue,
required,
...swaggerExtras,
}),
...(required ? [] : [IsOptional()]),
IsEnum(targetEnum),
]);
export const NotColumn = (
description?: string,
swaggerExtras: ApiPropertyOptions = {},
): PropertyDecorator =>
MergePropertyDecorators([
Exclude(),
ApiProperty({
description,
required: false,
readOnly: true,
...swaggerExtras,
}),
]);
"use strict";
exports.__esModule = true;
exports.EntityDescription = exports.EntityName = void 0;
var base_1 = require("./base");
var typeorm_1 = require("typeorm");
var EntityName = function (length, description) {
if (length === void 0) { length = 32; }
if (description === void 0) { description = '名称'; }
return (0, base_1.MergePropertyDecorators)([
(0, typeorm_1.Index)(),
(0, base_1.StringColumn)(length, description, undefined, true),
]);
};
exports.EntityName = EntityName;
var EntityDescription = function (length, description) {
if (length === void 0) { length = 5000; }
if (description === void 0) { description = '描述'; }
return (0, base_1.StringColumn)(length, description, '', false);
};
exports.EntityDescription = EntityDescription;
import { MergePropertyDecorators, StringColumn } from './base';
import { Index } from 'typeorm';
export const EntityName = (length = 32, description = '名称') =>
MergePropertyDecorators([
Index(),
StringColumn(length, description, undefined, true),
]);
export const EntityDescription = (length = 5000, description = '描述') =>
StringColumn(length, description, '', false);
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
exports.__esModule = true;
exports.StringRelationColumn = exports.RelationColumn = void 0;
var typeorm_1 = require("typeorm");
var base_1 = require("./base");
var swagger_1 = require("@nestjs/swagger");
var class_validator_1 = require("class-validator");
var bigint_transform_1 = require("../utility/bigint-transform");
var RelationColumn = function (description, notNull, columnExtras, propertyExtras) {
if (description === void 0) { description = '对应编号'; }
if (notNull === void 0) { notNull = false; }
if (columnExtras === void 0) { columnExtras = {}; }
if (propertyExtras === void 0) { propertyExtras = {}; }
return (0, base_1.MergePropertyDecorators)(__spreadArray(__spreadArray([
(0, typeorm_1.Column)('bigint', __assign({ nullable: !notNull, unsigned: true, transformer: new bigint_transform_1.BigintTransformer(), comment: description }, columnExtras)),
(0, swagger_1.ApiProperty)(__assign({ type: Number, description: description, required: notNull }, propertyExtras))
], (notNull ? [] : [(0, class_validator_1.IsOptional)()]), true), [
(0, class_validator_1.IsInt)(),
(0, class_validator_1.IsPositive)(),
], false));
};
exports.RelationColumn = RelationColumn;
var StringRelationColumn = function (description, notNull, columnExtras, propertyExtras) {
if (description === void 0) { description = '对应编号'; }
if (notNull === void 0) { notNull = false; }
if (columnExtras === void 0) { columnExtras = {}; }
if (propertyExtras === void 0) { propertyExtras = {}; }
return (0, base_1.MergePropertyDecorators)(__spreadArray(__spreadArray([
(0, typeorm_1.Column)('varchar', __assign({ length: 32, nullable: !notNull, comment: description }, columnExtras)),
(0, swagger_1.ApiProperty)(__assign({ type: String, required: notNull, description: description }, propertyExtras))
], (notNull ? [] : [(0, class_validator_1.IsOptional)()]), true), [
(0, class_validator_1.IsNotEmpty)(),
], false));
};
exports.StringRelationColumn = StringRelationColumn;
import { Column } from 'typeorm';
import { MergePropertyDecorators } from './base';
import { ApiProperty, ApiPropertyOptions } from '@nestjs/swagger';
import { IsInt, IsNotEmpty, IsOptional, IsPositive } from 'class-validator';
import { BigintTransformer } from '../utility/bigint-transform';
import { ColumnCommonOptions } from 'typeorm/decorator/options/ColumnCommonOptions';
import { ColumnWithLengthOptions } from 'typeorm/decorator/options/ColumnWithLengthOptions';
import { ColumnWithWidthOptions } from 'typeorm/decorator/options/ColumnWithWidthOptions';
export const RelationColumn = (
description = '对应编号',
notNull = false,
columnExtras: ColumnCommonOptions & ColumnWithWidthOptions = {},
propertyExtras: ApiPropertyOptions = {},
) =>
MergePropertyDecorators([
Column('bigint', {
nullable: !notNull,
unsigned: true,
transformer: new BigintTransformer(),
comment: description,
...columnExtras,
}),
ApiProperty({
type: Number,
description,
required: notNull,
...propertyExtras,
}),
...(notNull ? [] : [IsOptional()]),
IsInt(),
IsPositive(),
]);
export const StringRelationColumn = (
description = '对应编号',
notNull = false,
columnExtras: ColumnCommonOptions & ColumnWithLengthOptions = {},
propertyExtras: ApiPropertyOptions = {},
) =>
MergePropertyDecorators([
Column('varchar', {
length: 32,
nullable: !notNull,
comment: description,
...columnExtras,
}),
ApiProperty({
type: String,
required: notNull,
description,
...propertyExtras,
}),
...(notNull ? [] : [IsOptional()]),
IsNotEmpty(),
]);
"use strict";
exports.__esModule = true;
exports.NotChangeable = exports.NotWritable = void 0;
var class_transformer_1 = require("class-transformer");
var base_1 = require("./base");
var class_validator_1 = require("class-validator");
var NotWritable = function () {
return (0, base_1.MergePropertyDecorators)([(0, class_transformer_1.Expose)({ groups: ['r'] }), (0, class_validator_1.IsOptional)()]);
};
exports.NotWritable = NotWritable;
var NotChangeable = function () { return (0, class_transformer_1.Expose)({ groups: ['r', 'c'] }); };
exports.NotChangeable = NotChangeable;
import { Expose } from 'class-transformer';
import { MergePropertyDecorators } from './base';
import { IsOptional } from 'class-validator';
export const NotWritable = () =>
MergePropertyDecorators([Expose({ groups: ['r'] }), IsOptional()]);
export const NotChangeable = () => Expose({ groups: ['r', 'c'] });
"use strict";
exports.__esModule = true;
import { SelectQueryBuilder } from 'typeorm';
export interface QueryWise<T> {
applyQuery(qb: SelectQueryBuilder<T>, entityName: string): void;
}
"use strict";
exports.__esModule = true;
export interface IdWise {
id: number;
}
export interface StringIdWise {
id: string;
}
export interface NameWise {
name: string;
}
export interface DescWise {
desc: string;
}
export interface NameDescWise extends NameWise, DescWise {}
export interface IdNameWise extends IdWise, NameWise {}
export interface StringIdNameWise extends StringIdWise, NameWise {}
export interface IdNameDescWise extends IdWise, NameDescWise {}
export interface StringIdNameDescWise extends StringIdNameWise, DescWise {}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.RankRecord = void 0;
var openapi = require("@nestjs/swagger");
var typeorm_1 = require("typeorm");
var IdBase_entity_1 = require("./bases/IdBase.entity");
var base_1 = require("./decorators/base");
var class_validator_1 = require("class-validator");
var swagger_1 = require("@nestjs/swagger");
var query_1 = require("./utility/query");
var RankRecord = /** @class */ (function (_super) {
__extends(RankRecord, _super);
function RankRecord() {
return _super !== null && _super.apply(this, arguments) || this;
}
RankRecord.prototype.fromSession = function (session) {
this.userId = session.userId;
this.guildId = session.guildId;
this.rankDate = new Date();
return this;
};
RankRecord.prototype.applyQuery = function (qb, entityName) {
_super.prototype.applyQuery.call(this, qb, entityName);
(0, query_1.applyQueryProperty)(this, qb, entityName, 'userId', 'guildId', 'rankDate');
(0, query_1.applyQueryPropertySearch)(this, qb, entityName, 'rankName');
};
RankRecord._OPENAPI_METADATA_FACTORY = function () {
return { userId: { required: true, type: function () { return String; } }, guildId: { required: true, type: function () { return String; } }, rankDate: { required: true, type: function () { return Date; } }, rankName: { required: true, type: function () { return String; } } };
};
__decorate([
(0, typeorm_1.Index)(),
(0, base_1.StringColumn)(11, 'User ID', undefined, true)
], RankRecord.prototype, "userId");
__decorate([
(0, typeorm_1.Index)(),
(0, base_1.StringColumn)(11, 'Guild ID', undefined, true)
], RankRecord.prototype, "guildId");
__decorate([
(0, typeorm_1.Index)(),
(0, typeorm_1.Column)({ type: 'timestamp' }),
(0, class_validator_1.IsDate)(),
(0, swagger_1.ApiProperty)({ type: Date, description: 'The date of the rank given' })
], RankRecord.prototype, "rankDate");
__decorate([
(0, typeorm_1.Index)(),
(0, base_1.StringColumn)(6, 'Rank content', undefined, true)
], RankRecord.prototype, "rankName");
RankRecord = __decorate([
(0, typeorm_1.Entity)()
], RankRecord);
return RankRecord;
}(IdBase_entity_1.IdBase));
exports.RankRecord = RankRecord;
import { Column, Entity, Index, SelectQueryBuilder } from 'typeorm';
import { IdBase } from './bases/IdBase.entity';
import { StringColumn } from './decorators/base';
import { IsDate } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { Session } from 'koishi';
import { applyQueryProperty, applyQueryPropertySearch } from './utility/query';
@Entity()
export class RankRecord extends IdBase {
@Index()
@StringColumn(11, 'User ID', undefined, true)
userId: string;
@Index()
@StringColumn(11, 'Guild ID', undefined, true)
guildId: string;
@Index()
@Column({ type: 'timestamp' })
@IsDate()
@ApiProperty({ type: Date, description: 'The date of the rank given' })
rankDate: Date;
@Index()
@StringColumn(6, 'Rank content', undefined, true)
rankName: string;
fromSession(session: Session) {
this.userId = session.userId;
this.guildId = session.guildId;
this.rankDate = new Date();
return this;
}
override applyQuery(qb: SelectQueryBuilder<RankRecord>, entityName: string) {
super.applyQuery(qb, entityName);
applyQueryProperty(this, qb, entityName, 'userId', 'guildId', 'rankDate');
applyQueryPropertySearch(this, qb, entityName, 'rankName');
}
}
"use strict";
exports.__esModule = true;
exports.BigintTransformer = void 0;
var BigintTransformer = /** @class */ (function () {
function BigintTransformer() {
}
BigintTransformer.prototype.from = function (dbValue) {
if (dbValue == null) {
return dbValue;
}
return parseInt(dbValue);
};
BigintTransformer.prototype.to = function (entValue) {
return entValue;
};
return BigintTransformer;
}());
exports.BigintTransformer = BigintTransformer;
import { ValueTransformer } from 'typeorm';
export class BigintTransformer implements ValueTransformer {
from(dbValue) {
if (dbValue == null) {
return dbValue;
}
return parseInt(dbValue);
}
to(entValue): any {
return entValue;
}
}
"use strict";
exports.__esModule = true;
exports.applyQueryPropertySearch = exports.applyQueryPropertyLike = exports.applyQueryProperty = void 0;
function applyQueryProperty(obj, qb, entityName) {
var _a;
var fields = [];
for (var _i = 3; _i < arguments.length; _i++) {
fields[_i - 3] = arguments[_i];
}
for (var _b = 0, fields_1 = fields; _b < fields_1.length; _b++) {
var field = fields_1[_b];
if (obj[field] == null) {
continue;
}
qb.andWhere("".concat(entityName, ".").concat(field, " = :").concat(field), (_a = {}, _a[field] = obj[field], _a));
}
}
exports.applyQueryProperty = applyQueryProperty;
function applyQueryPropertyLike(obj, qb, entityName) {
var _a;
var fields = [];
for (var _i = 3; _i < arguments.length; _i++) {
fields[_i - 3] = arguments[_i];
}
for (var _b = 0, fields_2 = fields; _b < fields_2.length; _b++) {
var field = fields_2[_b];
if (obj[field] == null) {
continue;
}
qb.andWhere("".concat(entityName, ".").concat(field, " like (:").concat(field, " || '%')"), (_a = {},
_a[field] = obj[field],
_a));
}
}
exports.applyQueryPropertyLike = applyQueryPropertyLike;
function applyQueryPropertySearch(obj, qb, entityName) {
var _a;
var fields = [];
for (var _i = 3; _i < arguments.length; _i++) {
fields[_i - 3] = arguments[_i];
}
for (var _b = 0, fields_3 = fields; _b < fields_3.length; _b++) {
var field = fields_3[_b];
if (obj[field] == null) {
continue;
}
qb.andWhere("".concat(entityName, ".").concat(field, " like ('%' || :").concat(field, " || '%')"), (_a = {},
_a[field] = obj[field],
_a));
}
}
exports.applyQueryPropertySearch = applyQueryPropertySearch;
import { TimeBase } from '../bases/TimeBase.entity';
import { SelectQueryBuilder } from 'typeorm';
export function applyQueryProperty<T extends TimeBase>(
obj: T,
qb: SelectQueryBuilder<T>,
entityName: string,
...fields: (keyof T)[]
) {
for (const field of fields) {
if (obj[field] == null) {
continue;
}
qb.andWhere(`${entityName}.${field} = :${field}`, { [field]: obj[field] });
}
}
export function applyQueryPropertyLike<T extends TimeBase>(
obj: T,
qb: SelectQueryBuilder<T>,
entityName: string,
...fields: (keyof T)[]
) {
for (const field of fields) {
if (obj[field] == null) {
continue;
}
qb.andWhere(`${entityName}.${field} like (:${field} || '%')`, {
[field]: obj[field],
});
}
}
export function applyQueryPropertySearch<T extends TimeBase>(
obj: T,
qb: SelectQueryBuilder<T>,
entityName: string,
...fields: (keyof T)[]
) {
for (const field of fields) {
if (obj[field] == null) {
continue;
}
qb.andWhere(`${entityName}.${field} like ('%' || :${field} || '%')`, {
[field]: obj[field],
});
}
}
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
var core_1 = require("@nestjs/core");
var swagger_1 = require("@nestjs/swagger");
var app_module_1 = require("./app.module");
var koishi_nestjs_1 = require("koishi-nestjs");
function bootstrap() {
return __awaiter(this, void 0, void 0, function () {
var app, documentConfig, document;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, core_1.NestFactory.create(app_module_1.AppModule)];
case 1:
app = _a.sent();
app.useWebSocketAdapter(new koishi_nestjs_1.KoishiWsAdapter(app));
app.enableCors();
app.set('trust proxy', ['172.16.0.0/12', 'loopback']);
documentConfig = new swagger_1.DocumentBuilder()
.setTitle('rank-provide-bot')
.setDescription('A rank provide bot.')
.setVersion('1.0')
.build();
document = swagger_1.SwaggerModule.createDocument(app, documentConfig);
swagger_1.SwaggerModule.setup('docs', app, document);
return [4 /*yield*/, app.listen(3000)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
}
bootstrap();
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { KoishiWsAdapter } from 'koishi-nestjs';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useWebSocketAdapter(new KoishiWsAdapter(app));
app.enableCors();
app.set('trust proxy', ['172.16.0.0/12', 'loopback']);
const documentConfig = new DocumentBuilder()
.setTitle('rank-provide-bot')
.setDescription('A rank provide bot.')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, documentConfig);
SwaggerModule.setup('docs', app, document);
await app.listen(3000);
}
bootstrap();
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.RecordService = void 0;
var common_1 = require("@nestjs/common");
var crud_base_1 = require("../crud-base/crud-base");
var rank_record_entity_1 = require("../entities/rank-record.entity");
var typeorm_1 = require("@nestjs/typeorm");
var moment_1 = require("moment");
var typeorm_2 = require("typeorm");
var RecordService = /** @class */ (function (_super) {
__extends(RecordService, _super);
function RecordService(repo) {
return _super.call(this, rank_record_entity_1.RankRecord, repo) || this;
}
RecordService.prototype.isCanGiveRecord = function (session) {
return __awaiter(this, void 0, void 0, function () {
var previous;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.repo.findOne({
select: ['id'],
where: {
userId: session.userId,
guildId: session.guildId,
rankDate: (0, typeorm_2.MoreThanOrEqual)((0, moment_1["default"])().subtract(2, 'hours').toDate())
}
})];
case 1:
previous = _a.sent();
return [2 /*return*/, !previous];
}
});
});
};
RecordService.prototype.recordGiven = function (session, content) {
return __awaiter(this, void 0, void 0, function () {
var record, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
record = new rank_record_entity_1.RankRecord().fromSession(session);
record.rankName = content;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.create(record)];
case 2:
_a.sent();
return [2 /*return*/, true];
case 3:
e_1 = _a.sent();
return [2 /*return*/, false];
case 4: return [2 /*return*/];
}
});
});
};
RecordService = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, typeorm_1.InjectRepository)(rank_record_entity_1.RankRecord))
], RecordService);
return RecordService;
}(crud_base_1.CrudBase));
exports.RecordService = RecordService;
import { Test, TestingModule } from '@nestjs/testing';
import { RecordService } from './record.service';
describe('RecordService', () => {
let service: RecordService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [RecordService],
}).compile();
service = module.get<RecordService>(RecordService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { Injectable } from '@nestjs/common';
import { CrudBase } from '../crud-base/crud-base';
import { RankRecord } from '../entities/rank-record.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Session } from 'koishi';
import moment from 'moment';
import { MoreThanOrEqual } from 'typeorm';
@Injectable()
export class RecordService extends CrudBase<RankRecord> {
constructor(@InjectRepository(RankRecord) repo) {
super(RankRecord, repo);
}
async isCanGiveRecord(session: Session) {
const previous = await this.repo.findOne({
select: ['id'],
where: {
userId: session.userId,
guildId: session.guildId,
rankDate: MoreThanOrEqual(moment().subtract(2, 'hours').toDate()),
},
});
return !previous;
}
async recordGiven(session: Session, content: string) {
const record = new RankRecord().fromSession(session);
record.rankName = content;
try {
await this.create(record);
return true;
} catch (e) {
return false;
}
}
}
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.UpdatePipe = exports.ClassGetPipe = exports.GetPipe = exports.CreatePipe = void 0;
var common_1 = require("@nestjs/common");
var class_transformer_1 = require("class-transformer");
exports.CreatePipe = new common_1.ValidationPipe({
transform: true,
transformOptions: { groups: ['c'], enableImplicitConversion: true }
});
exports.GetPipe = new common_1.ValidationPipe({
transform: true,
transformOptions: { groups: ['r'], enableImplicitConversion: true },
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true
});
var ClassGetPipe = /** @class */ (function (_super) {
__extends(ClassGetPipe, _super);
function ClassGetPipe(classConstructor) {
var _this = _super.call(this, {
transform: false,
transformOptions: {
groups: ['r'],
enableImplicitConversion: true
},
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true
}) || this;
_this.classConstructor = classConstructor;
return _this;
}
ClassGetPipe.prototype.transform = function (value, metadata) {
return __awaiter(this, void 0, void 0, function () {
var obj;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, _super.prototype.transform.call(this, value, metadata)];
case 1:
obj = _a.sent();
return [2 /*return*/, (0, class_transformer_1.plainToClass)(this.classConstructor, obj, {
groups: ['r'],
enableImplicitConversion: false
})];
}
});
});
};
return ClassGetPipe;
}(common_1.ValidationPipe));
exports.ClassGetPipe = ClassGetPipe;
exports.UpdatePipe = new common_1.ValidationPipe({
transform: true,
transformOptions: { groups: ['u'], enableImplicitConversion: true },
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true
});
import { ValidationPipe } from '@nestjs/common';
import { ClassConstructor, plainToClass } from 'class-transformer';
export const CreatePipe = new ValidationPipe({
transform: true,
transformOptions: { groups: ['c'], enableImplicitConversion: true },
});
export const GetPipe = new ValidationPipe({
transform: true,
transformOptions: { groups: ['r'], enableImplicitConversion: true },
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true,
});
export class ClassGetPipe<T> extends ValidationPipe {
constructor(private readonly classConstructor: ClassConstructor<T>) {
super({
transform: false,
transformOptions: {
groups: ['r'],
enableImplicitConversion: true,
},
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true,
});
}
override async transform(value: any, metadata: any) {
const obj = await super.transform(value, metadata);
return plainToClass(this.classConstructor, obj, {
groups: ['r'],
enableImplicitConversion: false,
});
}
}
export const UpdatePipe = new ValidationPipe({
transform: true,
transformOptions: { groups: ['u'], enableImplicitConversion: true },
skipMissingProperties: true,
skipNullProperties: true,
skipUndefinedProperties: true,
});
......@@ -15,10 +15,10 @@ describe('AppController (e2e)', () => {
await app.init();
});
it('/ (GET)', () => {
/* it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
}); */
});
......@@ -6,16 +6,14 @@
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"target": "es2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
"esModuleInterop": true,
"skipLibCheck": 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