Commit b5ee6c96 authored by nanahira's avatar nanahira

first

parent 2d5d965e
Pipeline #6046 passed with stages
in 35 seconds
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
/build
/dist
/output
/config.yaml
.idea
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/output
/dest
/config.yaml
.idea
.dockerignore
Dockerfile
/src
.eslintrc.js
.prettierrc
webpack.config.js
tsconfig.json
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
MIT License
Copyright (c) 2019-present Shigma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Koishi Nestjs # Koishi Nestjs
Koishi.js as NestModule Koishi.js as NestModule
\ No newline at end of file
Only Koishi v4 is supported.
## Configuration
### Sync
```ts
import { Module } from '@nestjs/common';
import { KoishiModule, PluginDef } from 'koishi-nestjs';
import PluginOnebot from '@koishijs/plugin-onebot';
@Module({
imports: [
KoishiModule.register({
// Koishi config goes here
usePlugins: [
// Plugins to install
PluginDef(PluginOnebot, {
protocol: 'ws',
endpoint: config.get('CQ_ENDPOINT'),
selfId: config.get('CQ_SELFID'),
token: config.get('CQ_TOKEN'),
}),
],
})
]
})
export class AppModule {}
```
You may also register Koishi plugins later.
### Async
```ts
import { Module } from '@nestjs/common';
import { KoishiModule, PluginDef } from 'koishi-nestjs';
import PluginOnebot from '@koishijs/plugin-onebot';
@Module({
imports: [
KoishiModule.registerAsync({
useFactory: () => ({
// Koishi config goes here
usePlugins: [
// Plugins to install
PluginDef(PluginOnebot, {
protocol: 'ws',
endpoint: config.get('CQ_ENDPOINT'),
selfId: config.get('CQ_SELFID'),
token: config.get('CQ_TOKEN'),
}),
],
})
})
]
})
export class AppModule {}
```
## Injection of Koishi App or Context
### Inject Koishi instance
```ts
@Injectable()
export class AppService {
constructor(private koishi: KoishiService) {}
}
```
### Inject Context
```ts
import { Injectable } from '@nestjs/common';
import { KoishiService, InjectContext } from 'koishi-nestjs';
import { Context } from 'koishi';
@Injectable()
export class AppService {
constructor(@InjectContext() private ctx: Context) {}
}
```
### Inject Context of private chat
```ts
import { Injectable } from '@nestjs/common';
import { KoishiService, InjectContextPrivate } from 'koishi-nestjs';
import { Context } from 'koishi';
@Injectable()
export class AppService {
constructor(@InjectContextPrivate() private ctx: Context) {}
}
```
### Inject Context of channel
```ts
import { Injectable } from '@nestjs/common';
import { KoishiService, InjectContextChannel } from 'koishi-nestjs';
import { Context } from 'koishi';
@Injectable()
export class AppService {
constructor(@InjectContextChannel() private ctx: Context) {}
}
```
export * from './src/koishi.constants'
export * from './src/koishi.decorators'
export * from './src/koishi.interfaces'
export * from './src/koishi.service'
export * from './src/koishi.module'
#!/bin/bash
npm install --save \
lodash
npm install --save-dev \
@types/node \
@types/lodash \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier
This diff is collapsed.
{
"name": "koishi-nestjs",
"version": "1.0.0",
"description": "Koishi.js as Nest.js Module",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "tsc"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/nanahira/koishi-nestjs.git"
},
"bugs": {
"url": "https://code.mycard.moe/nanahira/koishi-nestjs/issues"
},
"homepage": "https://code.mycard.moe/nanahira/koishi-nestjs",
"keywords": [
"Koishi.js",
"Nest.js",
"nest",
"koishi",
"qqbot",
"cqhttp",
"cqbot",
"koishijs",
"nestjs"
],
"author": "Nanahira",
"license": "MIT",
"peerDependencies": {
"@nestjs/core": "^7.0.0 || ^8.0.0",
"@nestjs/common": "^7.0.0 || ^8.0.0",
"reflect-metadata": "^0.1.13"
},
"devDependencies": {
"@nestjs/common": "^8.0.9",
"@nestjs/core": "^8.0.9",
"@types/node": "^16.10.2",
"@typescript-eslint/eslint-plugin": "^4.32.0",
"@typescript-eslint/parser": "^4.32.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"prettier": "^2.4.1",
"reflect-metadata": "^0.1.13",
"typescript": "^4.4.3"
},
"dependencies": {
"koishi": "^4.0.0-alpha.8",
"proxy-agent": "^5.0.0"
}
}
export const KOISHI_MODULE_OPTIONS = 'KOISHI_MODULE_OPTIONS';
export const KOISHI_CONTEXT = 'KOISHI_CONTEXT';
export const KOISHI_CONTEXT_PRIVATE = 'KOISHI_CONTEXT_PRIVATE';
export const KOISHI_CONTEXT_CHANNEL = 'KOISHI_CONTEXT_CHANNEL';
import { Inject } from '@nestjs/common';
import {
KOISHI_CONTEXT,
KOISHI_CONTEXT_CHANNEL,
KOISHI_CONTEXT_PRIVATE,
} from './koishi.constants';
export const InjectContext = () => Inject(KOISHI_CONTEXT);
export const InjectContextPrivate = () => Inject(KOISHI_CONTEXT_PRIVATE);
export const InjectContextChannel = () => Inject(KOISHI_CONTEXT_CHANNEL);
import { ModuleMetadata, Provider, Type } from '@nestjs/common';
import { App, Plugin, MaybeArray } from 'koishi';
const selectors = [
'user',
'guild',
'channel',
'self',
'private',
'platform',
] as const;
type SelectorType = typeof selectors[number];
type SelectorValue = boolean | MaybeArray<string | number>;
type BaseSelection = { [K in SelectorType as `$${K}`]?: SelectorValue };
export interface Selection extends BaseSelection {
$and?: Selection[];
$or?: Selection[];
$not?: Selection;
}
export interface KoishiModulePlugin<T extends Plugin> {
plugin: T;
options?: boolean | Plugin.Config<T>;
select?: Selection;
}
export function PluginDef<T extends Plugin>(
plugin: T,
options?: boolean | Plugin.Config<T>,
select?: Selection,
): KoishiModulePlugin<T> {
return { plugin, options, select };
}
export interface KoishiModuleOptions extends App.Config {
usePlugins?: KoishiModulePlugin<Plugin>[];
}
export interface KoishiModuleOptionsFactory {
createKoishiOptions(): Promise<KoishiModuleOptions> | KoishiModuleOptions;
}
export interface KoishiModuleAsyncOptions
extends Pick<ModuleMetadata, 'imports'> {
useExisting?: Type<KoishiModuleOptionsFactory>;
useClass?: Type<KoishiModuleOptionsFactory>;
useFactory?: (
...args: any[]
) => Promise<KoishiModuleOptions> | KoishiModuleOptions;
inject?: any[];
extraProviders?: Provider[];
}
import {
DynamicModule,
Module,
OnApplicationShutdown,
Provider,
} from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import {
KoishiModuleAsyncOptions,
KoishiModuleOptions,
KoishiModuleOptionsFactory,
} from './koishi.interfaces';
import { KoishiService } from './koishi.service';
import {
KOISHI_CONTEXT,
KOISHI_CONTEXT_CHANNEL,
KOISHI_CONTEXT_PRIVATE,
KOISHI_MODULE_OPTIONS,
} from './koishi.constants';
import { Context } from 'koishi';
const koishiContextProvider: Provider = {
provide: Context,
useFactory: (koishiApp: KoishiService) => koishiApp.any(),
};
const koishiContextProviderAny: Provider = {
provide: KOISHI_CONTEXT,
useFactory: (koishiApp: KoishiService) => koishiApp.any(),
};
const koishiContextProviderChannel: Provider = {
provide: KOISHI_CONTEXT_CHANNEL,
useFactory: (koishiApp: KoishiService) => koishiApp.channel(),
};
const koishiContextProviderPrivate: Provider = {
provide: KOISHI_CONTEXT_PRIVATE,
useFactory: (koishiApp: KoishiService) => koishiApp.private(),
};
@Module({
providers: [
KoishiService,
koishiContextProvider,
koishiContextProviderAny,
koishiContextProviderChannel,
koishiContextProviderPrivate,
],
exports: [
KoishiService,
koishiContextProvider,
koishiContextProviderAny,
koishiContextProviderChannel,
koishiContextProviderPrivate,
],
})
export class KoishiModule implements OnApplicationShutdown {
constructor(private readonly moduleRef: ModuleRef) {}
static register(options: KoishiModuleOptions): DynamicModule {
return {
module: KoishiModule,
providers: [{ provide: KOISHI_MODULE_OPTIONS, useValue: options }],
};
}
static registerAsync(options: KoishiModuleAsyncOptions): DynamicModule {
return {
module: KoishiModule,
imports: options.imports,
providers: this.createAsyncProviders(options),
};
}
private static createAsyncProviders(
options: KoishiModuleAsyncOptions,
): Provider[] {
if (options.useExisting || options.useFactory) {
return [this.createAsyncOptionsProvider(options)];
}
return [
this.createAsyncOptionsProvider(options),
{
provide: options.useClass,
useClass: options.useClass,
},
];
}
private static createAsyncOptionsProvider(
options: KoishiModuleAsyncOptions,
): Provider {
if (options.useFactory) {
return {
provide: KOISHI_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject || [],
};
}
return {
provide: KOISHI_MODULE_OPTIONS,
useFactory: async (optionsFactory: KoishiModuleOptionsFactory) =>
optionsFactory.createKoishiOptions(),
inject: [options.useExisting || options.useClass],
};
}
async onApplicationShutdown() {
const koishiApp = this.moduleRef.get(KoishiService);
await koishiApp.stop();
}
}
import { App } from 'koishi';
import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { KOISHI_MODULE_OPTIONS } from './koishi.constants';
import { KoishiModuleOptions } from './koishi.interfaces';
@Injectable()
export class KoishiService extends App implements OnModuleInit {
constructor(
@Inject(KOISHI_MODULE_OPTIONS)
private koishiModuleOptions: KoishiModuleOptions,
) {
super(koishiModuleOptions);
}
async onModuleInit() {
if (this.koishiModuleOptions.usePlugins) {
for (const pluginDesc of this.koishiModuleOptions.usePlugins) {
const ctx = pluginDesc.select
? this.select(pluginDesc.select)
: this.any();
ctx.plugin(pluginDesc.plugin, pluginDesc.options);
}
}
return this.start();
}
}
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true,
"skipLibCheck": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts"
]
}
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