Skip to content

Commit

Permalink
refa: refactor internal services
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Oct 22, 2023
1 parent fef2844 commit 9cdb980
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 147 deletions.
2 changes: 1 addition & 1 deletion adapters/lark/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class LarkBot extends Bot<LarkBot.Config> {
'Content-Type': 'application/json; charset=utf-8',
},
})
this.assetsQuester = Quester.create()
this.assetsQuester = ctx.http

this.internal = new Internal(this.http)

Expand Down
101 changes: 41 additions & 60 deletions packages/axios/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Context } from 'cordis'
import { Agent } from 'agent-base'
import { arrayBufferToBase64, base64ToArrayBuffer, Dict, pick, trimSlash } from 'cosmokit'
import { ClientRequestArgs } from 'http'
Expand All @@ -7,18 +6,6 @@ import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'
import * as Axios from 'axios'
import { isPrivate } from './ip'

declare module 'cordis' {
interface Context {
http: Quester
}

namespace Context {
interface Config {
request?: Quester.Config
}
}
}

export interface Quester {
<T = any>(method: Method, url: string, config?: AxiosRequestConfig): Promise<T>
axios<T = any>(config?: AxiosRequestConfig): Promise<AxiosResponse<T>>
Expand All @@ -27,12 +14,50 @@ export interface Quester {
}

export class Quester {
constructor(ctx: Context, config: Context.Config) {
return Quester.create(config.request)
constructor(config: Quester.Config) {
const request = async (config: AxiosRequestConfig = {}) => {
const options = http.prepare()
const error = new Error() as Axios.AxiosError
return axios({
...options,
...config,
url: http.resolve(config.url!),
headers: {
...options.headers,
...config.headers,
},
}).catch((cause) => {
if (!axios.isAxiosError(cause)) throw cause
Object.assign(error, cause)
error.isAxiosError = true
error.cause = cause
throw error
})
}

const http = (async (method, url, config) => {
const response = await request({ url, ...config, method })
return response.data
}) as Quester

Object.setPrototypeOf(http, Object.getPrototypeOf(this))
for (const key of ['extend', 'get', 'delete', 'post', 'put', 'patch', 'head', 'ws']) {
http[key] = this[key].bind(http)
}

http.config = config
http.axios = (...args: any[]) => {
if (typeof args[0] === 'string') {
return request({ url: args[0], ...args[1] })
} else {
return request(args[0])
}
}
return http
}

extend(newConfig: Quester.Config): Quester {
return Quester.create({
return new Quester({
...this.config,
...newConfig,
headers: {
Expand Down Expand Up @@ -171,50 +196,6 @@ export namespace Quester {
timeout?: number
proxyAgent?: string
}

export function create(this: typeof Quester, config: Quester.Config = {}) {
const request = async (config: AxiosRequestConfig = {}) => {
const options = http.prepare()
const error = new Error() as Axios.AxiosError
return axios({
...options,
...config,
url: http.resolve(config.url!),
headers: {
...options.headers,
...config.headers,
},
}).catch((cause) => {
if (!axios.isAxiosError(cause)) throw cause
Object.assign(error, cause)
error.isAxiosError = true
error.cause = cause
throw error
})
}

const http = (async (method, url, config) => {
const response = await request({ url, ...config, method })
return response.data
}) as Quester

Object.setPrototypeOf(http, this.prototype)
for (const key of ['extend', 'get', 'delete', 'post', 'put', 'patch', 'head', 'ws']) {
http[key] = this.prototype[key].bind(http)
}

http.config = config
http.axios = (...args: any[]) => {
if (typeof args[0] === 'string') {
return request({ url: args[0], ...args[1] })
} else {
return request(args[0])
}
}
return http
}
}

Context.service('http', Quester)

export default Quester
8 changes: 4 additions & 4 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@
},
"dependencies": {
"@satorijs/element": "^2.5.1",
"@satorijs/protocol": "^1.0.2",
"cordis": "^2.9.2",
"cordis-axios": "^3.3.2",
"@satorijs/protocol": "^1.1.0",
"cordis": "^2.10.0",
"cordis-axios": "^4.0.0",
"cosmokit": "^1.5.1",
"ws": "^8.14.2",
"reggol": "^1.5.2",
"schemastery": "^3.13.1"
"schemastery": "^3.14.0"
}
}
82 changes: 51 additions & 31 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import Schema from 'schemastery'
import Logger from 'reggol'
import Quester from 'cordis-axios'
import { SendOptions } from '@satorijs/protocol'
import { Internal } from './internal'
import h from '@satorijs/element'

h.warn = new Logger('element').warn
Expand All @@ -23,7 +22,6 @@ export * as Universal from '@satorijs/protocol'

export * from './bot'
export * from './adapter'
export * from './internal'
export * from './message'
export * from './session'

Expand All @@ -48,6 +46,14 @@ Quester.createConfig = function createConfig(this, endpoint) {
}).description('请求设置')
}

export type Component = h.Render<Awaitable<h.Fragment>, Session>

export namespace Component {
export interface Options {
session?: boolean
}
}

type EventCallback<T = void, R extends any[] = []> = (this: Session, session: Session, ...args: R) => T

export interface Events<C extends Context = Context> extends cordis.Events<C> {
Expand Down Expand Up @@ -92,14 +98,34 @@ export interface Events<C extends Context = Context> extends cordis.Events<C> {
export interface Context {
[Context.config]: Context.Config
[Context.events]: Events<this>
bots: Bot[] & Dict<Bot>
http: Quester
}

export class Context extends cordis.Context {
static readonly session = Symbol('session')

constructor(options?: Context.Config) {
super(options)
public bots = new Proxy([] as Bot[] & Dict<Bot>, {
get(target, prop) {
if (prop in target || typeof prop === 'symbol') {
return Reflect.get(target, prop)
}
return target.find(bot => bot.sid === prop)
},
deleteProperty(target, prop) {
if (prop in target || typeof prop === 'symbol') {
return Reflect.deleteProperty(target, prop)
}
const bot = target.findIndex(bot => bot.sid === prop)
if (bot < 0) return true
target.splice(bot, 1)
return true
},
})

constructor(config: Context.Config = {}) {
super(config)

this.http = new Quester(config.request)

this.on('internal/warning', (format, ...args) => {
this.logger('app').warn(format, ...args)
Expand All @@ -109,10 +135,29 @@ export class Context extends cordis.Context {
logger(name: string) {
return new Logger(name)
}

component(name: string, component: Component, options: Component.Options = {}) {
const render: Component = async (attrs, children, session) => {
if (options.session && session.type === 'send') {
throw new Error('interactive components is not available outside sessions')
}
const result = await component(attrs, children, session)
return session.transform(h.normalize(result))
}
const service = 'component:' + name
this.root.provide(service)
this[service] = render
return this.collect('component', () => {
this[service] = null
return true
})
}
}

export namespace Context {
export interface Config extends cordis.Context.Config {}
export interface Config extends cordis.Context.Config {
request?: Quester.Config
}

export const Config: Config.Static = Schema.intersect([
Schema.object({}),
Expand All @@ -122,28 +167,3 @@ export namespace Context {
export interface Static extends Schema<Config> {}
}
}

Context.service('internal', Internal)

Context.service('bots', class {
constructor(root: Context) {
const list: Bot[] = []
return new Proxy(list, {
get(target, prop) {
if (prop in target || typeof prop === 'symbol') {
return target[prop]
}
return list.find(bot => bot.sid === prop)
},
deleteProperty(target, prop) {
if (prop in target || typeof prop === 'symbol') {
return delete target[prop]
}
const bot = target.findIndex(bot => bot.sid === prop)
if (bot < 0) return true
target.splice(bot, 1)
return true
},
})
}
})
50 changes: 0 additions & 50 deletions packages/core/src/internal.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/protocol/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@satorijs/protocol",
"description": "Protocol types for Satori protocol",
"version": "1.0.2",
"version": "1.1.0",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"exports": {
Expand Down

0 comments on commit 9cdb980

Please sign in to comment.