Skip to content

Commit

Permalink
feat: service, cache, database and server
Browse files Browse the repository at this point in the history
  • Loading branch information
BIYUEHU committed Feb 7, 2024
1 parent 3689b96 commit 58a0ae0
Show file tree
Hide file tree
Showing 30 changed files with 1,495 additions and 197 deletions.
Empty file added kotori.db
Empty file.
4 changes: 4 additions & 0 deletions modules/random-img/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ const quick = (url: string, el: Elements) => el.image(url) || 'corei18n.template
export const lang = [__dirname, '../locales'];

export function main(ctx: Context) {
ctx.on('ready', () => {
ctx.logger.debug(ctx.db);
});

ctx.command('sex [tags] - random_img.descr.sex').action(async (data, session) => {
session.quick('random_img.msg.sex.tips');
const res = sexSchema.parse(
Expand Down
4 changes: 4 additions & 0 deletions modules/testing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export const inject = ['database'];

/* 插件入口 */
export function main(ctx: Context, config: Config) {
ctx.on('ready', () => {
ctx.logger.debug(ctx.db);
});

/* 事件监听 */
ctx.on('on_group_decrease', (session) => {
session.quick([
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@
"minimist": "^1.2.8",
"tsukiko": "^1.2.1"
}
}
}
8 changes: 6 additions & 2 deletions packages/core/src/components/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Config from './config';
import Message from './message';
import Modules from './modules';
import type { AdapterClass, EventsMapping } from '../types';
import type { Api } from '../service';
import { Cache, type Api } from '../service';

declare module '../context' {
interface Context extends Events<EventsMapping> {
Expand All @@ -32,6 +32,8 @@ declare module '../context' {
/* Inject */
http: Http;
i18n: I18n;
/* Service */
cache: Cache;
}
}

Expand All @@ -54,7 +56,9 @@ export class Core extends Context {
this.inject('http');
this.provide('i18n', new I18n({ lang: this.config.global.lang }));
this.inject('i18n');
this.inject('i18n');
this.provide('cache', new Cache(this));
this.on('ready', () => (this.get('cache') as Cache).start());
this.on('dispose', () => (this.get('cache') as Cache).stop());
}
}

Expand Down
23 changes: 15 additions & 8 deletions packages/core/src/components/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,28 @@ function checkConfig(schema: unknown, config: ModuleConfig) {
export class Modules {
private handleExports(identity: string, ctx: Context, exports: obj, config: ModuleConfig) {
/* before handle */
const { lang, config: schema, default: defaults, main, Main } = exports.default;
const { lang, inject, config: schema, default: defaults, main, Main } = exports.default;
if (lang) this.ctx.i18n.use(Array.isArray(lang) ? resolve(...lang) : resolve(lang));
/* handle */
/* service */
if (isServiceConsructor(defaults)) {
/* adapter */
return undefined;
}
/* adapter */
if (isAdapterClass(defaults)) {
const adapterName = identity.split(ADAPTER_PREFIX)[1];
// const databaseName = moduleName.split(DATABASE_PREFIX)[1];
if (adapterName && isAdapterClass(defaults)) {
this.ctx[Symbols.adapter].set(adapterName, [defaults, schema]);
} /* else if (databaseName && isDatabaseClass(default)) {
service and database
} */
if (adapterName) this.ctx[Symbols.adapter].set(adapterName, [defaults, schema]);
return undefined;
}
/* plugin */
if (inject && (typeof inject === 'string' || Array.isArray(inject))) {
(typeof inject === 'string' ? [inject] : (inject as string[])).forEach((identity) => {
this.ctx[Symbols.container].forEach((service, name) => {
if (!(service instanceof Service) || service.identity !== identity) return;
ctx.inject(name as Exclude<keyof Context, Symbols | number>);
});
});
}
const moduleConfig = checkConfig(schema, config);
if (moduleConfig instanceof TsuError)
return new ModuleError(`Config format of module ${identity} is error: ${moduleConfig.message}`);
Expand Down
13 changes: 10 additions & 3 deletions packages/core/src/context/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/*
* @Author: Hotaru [email protected]
* @Blog: https://hotaru.icu
* @Date: 2024-02-07 13:44:38
* @LastEditors: Hotaru [email protected]
* @LastEditTime: 2024-02-07 16:40:35
*/
import Symbols from './symbols';

interface obj {
Expand Down Expand Up @@ -57,7 +64,7 @@ export class Context implements ContextImpl {
this[Symbols.table].set(prop, keys);
keys.forEach((key) => {
if (this[key] || !instance[key]) return;
this[key] = instance[key];
this[key] = instance[key] as this[K];
if (typeof this[key] === 'function') this[key] = (this[key] as Function).bind(instance);
});
}
Expand All @@ -79,9 +86,9 @@ export class Context implements ContextImpl {
};
/* set proxy */
const ctx: Context = new Proxy(new Context(this.root), {
get: <T>(target: T, prop: keyof T) => {
get: <T extends Context>(target: T, prop: keyof T) => {
if (prop === 'identity') return identity ?? this.identity ?? 'sub';
if (target[prop]) return target[prop];
if (target[prop]) return handler(target[prop], target);
let value: unknown;
this[Symbols.table].forEach((keys, key) => {
if (value || (typeof prop === 'string' && !keys.includes(prop))) return;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/context/symbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export class Symbols {
static readonly containerKey = (prop: string) => Symbol.for(`kotori.context.container.${prop}`);

/* custom */
static readonly service = Symbol.for('kotori.core.service');
// static readonly service = Symbol.for('kotori.core.service');

static readonly adapter = Symbol.for('kotori.core.adapter');

Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/*
* @Author: Hotaru [email protected]
* @Blog: https://hotaru.icu
* @Date: 2024-02-07 13:44:38
* @LastEditors: Hotaru [email protected]
* @LastEditTime: 2024-02-07 14:47:23
*/
export * from './context';
export * from './components';
export * from './service';
Expand All @@ -8,4 +15,5 @@ export * from './utils/container';
export * from './consts';
export * from './types';
export * from '@kotori-bot/tools';
export * from '@kotori-bot/i18n';
export * from 'tsukiko';
13 changes: 9 additions & 4 deletions packages/core/src/service/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
AdapterConfig,
CommandResult
} from '../types';
import Service from './service';
import Elements from './elements';
import { cancelFactory } from '../utils/factory';
import CommandError from '../utils/commandError';
Expand All @@ -30,8 +29,9 @@ interface AdapterStatus {
offlineTimes: number;
}

interface AdapterImpl<T extends Api = Api> extends Service {
interface AdapterImpl<T extends Api = Api> {
readonly ctx: Context;
readonly config: AdapterConfig;
readonly platform: string;
readonly selfId: EventDataTargetId;
readonly identity: string;
Expand Down Expand Up @@ -95,15 +95,14 @@ function error<K extends keyof CommandResult>(type: K, data?: CommandResult[K])
return new CommandError(Object.assign(data ?? {}, { type }) as ConstructorParameters<typeof CommandError>[0]);
}

export abstract class Adapter<T extends Api = Api> extends Service implements AdapterImpl<T> {
export abstract class Adapter<T extends Api = Api> implements AdapterImpl<T> {
constructor(
ctx: Context,
config: AdapterConfig,
identity: string,
Api: new (adapter: Adapter) => T,
el: Elements = new Elements()
) {
super('adapter', '');
this.ctx = ctx;
this.config = config;
this.identity = identity;
Expand All @@ -114,6 +113,12 @@ export abstract class Adapter<T extends Api = Api> extends Service implements Ad
this.ctx[Symbols.bot].get(this.platform)!.add(this.api);
}

abstract handle(...data: unknown[]): void;

abstract start(): void;

abstract stop(): void;

abstract send(action: string, params?: object): void | object | Promise<unknown> | null | undefined;

protected online() {
Expand Down
31 changes: 18 additions & 13 deletions packages/core/src/service/cache.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import { none, obj } from '@kotori-bot/tools';
import Service from './service';

type CacheKey = string | symbol;
type CacheValue = string | number | object;

export class Cache extends Service {
private cacheStack?: obj;
private cache?: Map<CacheKey, CacheValue>;

constructor(ctx: ConstructorParameters<typeof Service>[0]) {
super(ctx, {}, 'cache');
}

constructor() {
super('custom', 'cache');
start() {
if (this.cache) return;
this.cache = new Map();
}

handle(data: unknown[]): void {
none(this);
stop() {
this.cache?.clear();
delete this.cache;
}

start(): void {
this.cacheStack = {};
get(prop: CacheKey) {
return this.cache!.get(prop);
}

stop(): void {
Object.keys(this.cacheStack!).forEach((key) => {
delete this.cacheStack![key];
});
delete this.cacheStack;
set(prop: CacheKey, value: CacheValue) {
this.cache!.set(prop, value);
}
}

Expand Down
9 changes: 0 additions & 9 deletions packages/core/src/service/database.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/core/src/service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ export * from './service';
export * from './adapter';
export * from './api';
export * from './elements';
export * from './database';
export * from './cache';
46 changes: 15 additions & 31 deletions packages/core/src/service/service.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import { none } from '@kotori-bot/tools';
import { Context } from '../context';

type ModuleType = 'database' | 'adapter' | 'service' | 'plugin';
type ServiceType = Exclude<ModuleType, 'plugin' | 'service'> | 'custom';

interface ServiceImpl {
readonly config: object;
readonly serviceType: ServiceType;
readonly service: string;
handle(...data: unknown[]): void;
interface ServiceImpl<T extends object = object> {
readonly identity: string;
readonly config: T;
start(): void;
stop(): void;
}

export abstract class Service implements ServiceImpl {
handle(...data: unknown[]): void {
return none(this, data);
export abstract class Service<T extends object = object> implements ServiceImpl<T> {
readonly ctx: Context;

readonly config: T;

readonly identity: string;

constructor(ctx: Context, config: T, identity: string) {
this.ctx = ctx;
this.config = config;
this.identity = identity;
}

start(): void {
Expand All @@ -24,26 +28,6 @@ export abstract class Service implements ServiceImpl {
stop(): void {
return none(this);
}

readonly serviceType: ServiceType;

readonly service: string;

readonly config: object;

constructor(serviceType: ServiceType, service: string, config: object = {}) {
this.serviceType = serviceType;
this.config = config;
if (serviceType === 'adapter') {
this.service = 'adapter';
return;
}
if (serviceType === 'database') {
this.service = 'database';
return;
}
this.service = service;
}
}

export default Service;
1 change: 0 additions & 1 deletion packages/core/src/types/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,3 @@ interface EventDataStatus {

export type ServiceClass = new (config: object) => Service;
export type AdapterClass = new (ctx: Context, config: AdapterConfig, identity: string) => Adapter;
// export type DatabaseClass = new (config: /* DatabaseConfig , identity: string */ /* object) => Database;
2 changes: 1 addition & 1 deletion packages/core/src/utils/errror.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type KotoriErrorType = 'DatabaseError' | 'ModuleError' | 'UnknownError' | 'DevError';
type KotoriErrorType = 'ServiceError' | 'ModuleError' | 'UnknownError' | 'DevError';

interface KotoriErrorImpl {
readonly name: KotoriErrorType;
Expand Down
5 changes: 3 additions & 2 deletions packages/kotori/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,11 @@ kotori 是一个**跨平台、解耦合、现代化**于一体的聊天机器人
- WeChat/微信
- Discord

#### Database(待支持)
#### Database

- Memory
- Sqlite
即将支持:
- Memory
- Mysql

---
Expand Down
2 changes: 2 additions & 0 deletions packages/kotori/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
],
"files": [
"lib",
"kotori.yml",
"bin.js",
"LICENSE",
"README.md"
],
Expand Down
4 changes: 2 additions & 2 deletions packages/kotori/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cac from 'cac';
import { Loader, Logger } from '@kotori-bot/loader';
import { readFileSync } from 'fs';
import { resolve } from 'path';

const program = cac();

Expand All @@ -12,8 +13,7 @@ program
.command('')
.option('--dir [path]', 'Set running root dir of program')
.action((options) => {
Logger.info(options);
new Loader({ mode: 'build' }).run();
new Loader({ mode: 'build', dir: resolve(process.cwd(), options.dir ?? '') }).run();
});

program
Expand Down
Loading

0 comments on commit 58a0ae0

Please sign in to comment.