Skip to content

Commit

Permalink
fix: improve event-core types
Browse files Browse the repository at this point in the history
  • Loading branch information
mav-rik committed Apr 19, 2023
1 parent d184e4c commit 713c665
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 46 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
"homepage": "https://github.com/wooksjs/wooksjs#readme",
"devDependencies": {
"@microsoft/api-extractor": "^7.33.6",
"@microsoft/api-extractor": "^7.34.4",
"@prostojs/dye": "^0.3.0",
"@prostojs/logger": "^0.3.4",
"@prostojs/router": "^0.0.16",
Expand Down
8 changes: 4 additions & 4 deletions packages/event-cli/src/event-cli.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { TEventOptions, createEventContext, useEventContext } from '@wooksjs/event-core'
import { TEmpty, TEventOptions, createEventContext, useEventContext } from '@wooksjs/event-core'
import { TCliContextStore, TCliEventData } from './types'

export function createCliContext(data: TCliEventData, options: TEventOptions) {
return createEventContext<TCliContextStore>({
return createEventContext<TCliContextStore, TCliEventData>({
event: {
...data,
type: 'CLI',
Expand All @@ -11,6 +11,6 @@ export function createCliContext(data: TCliEventData, options: TEventOptions) {
})
}

export function useCliContext<T extends object>() {
return useEventContext<TCliContextStore & T>('CLI')
export function useCliContext<T extends TEmpty>() {
return useEventContext<TCliContextStore & T, TCliEventData>('CLI')
}
1 change: 1 addition & 0 deletions packages/event-cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './event-cli'
export * from './cli-adapter'
export * from './composables'
export * from './types'
7 changes: 1 addition & 6 deletions packages/event-cli/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { TGenericEvent, TGenericContextStore } from '@wooksjs/event-core'

export interface TCliEventData {
argv: string[]
}

export interface TCliEvent extends TGenericEvent, TCliEventData {
type: 'CLI'
}

export interface TCliContextStore extends TGenericContextStore<TCliEvent> {
export interface TCliContextStore {
flags?: {
[name: string]: boolean | string
}
Expand Down
52 changes: 26 additions & 26 deletions packages/event-core/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { attachHook } from './hook'
import { TProstoLoggerOptions } from '@prostojs/logger'
import { TEventLoggerData } from './event-logger'
import { TGenericEvent } from './types'
import { TEmpty, TGenericEvent } from './types'

export interface TEventOptions {
eventLogger?: { topic?: string } & TProstoLoggerOptions<TEventLoggerData>
}

export type TGenericContextStore<E extends TGenericEvent = TGenericEvent> = {
event: E
export type TGenericContextStore<CustomEventType = TEmpty> = {
event: CustomEventType & TGenericEvent
options: TEventOptions
routeParams?: Record<string, string | string[]>
}
Expand All @@ -21,10 +21,10 @@ let currentContext: TGenericContextStore | null = null
* @param data
* @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
*/
export function createEventContext<S extends TGenericContextStore>(data: S) {
export function createEventContext<S = TEmpty, EventTypeToCreate = TEmpty>(data: S & TGenericContextStore<EventTypeToCreate>) {
const newContext = { ...data }
currentContext = newContext
return _getCtxHelpers<S>(newContext)
return _getCtxHelpers<S & TGenericContextStore<EventTypeToCreate>>(newContext)
}

/**
Expand All @@ -34,30 +34,30 @@ export function createEventContext<S extends TGenericContextStore>(data: S) {
*
* @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
*/
export function useEventContext<S extends TGenericContextStore>(expectedTypes?: string | string[]) {
export function useEventContext<S = TEmpty, EventType = TEmpty>(expectedTypes?: string | string[]) {
if (!currentContext) {
throw new Error('Event context does not exist. Use event context synchronously within the runtime of the event.')
}
const cc = currentContext as S
const cc = currentContext as (S & TGenericContextStore<EventType>)
if (expectedTypes || typeof expectedTypes === 'string') {
const type = cc.event?.type
const types = typeof expectedTypes === 'string' ? [ expectedTypes ] : expectedTypes
if (!types.includes(type)) new Error(`Event context type mismatch: expected ${ types.map(t => `"${ t }"`).join(', ') }, received "${ type }"`)
}

return _getCtxHelpers<S>(cc)
return _getCtxHelpers(cc)
}

function _getCtxHelpers<S extends TGenericContextStore>(cc: S) {
function _getCtxHelpers<T>(cc: T) {
/**
* Hook to an event store property
*
* @param key store property key
* @returns a hook { value: <prop value>, hook: (key2: keyof <prop value>) => { value: <nested prop value> }, ... }
*/
function store<K extends keyof Required<S>>(key: K) {
function store<K extends keyof Required<T>>(key: K) {
const obj = {
value: null as S[K],
value: null as T[K],
hook,
init,
set: setNested,
Expand All @@ -73,18 +73,18 @@ function _getCtxHelpers<S extends TGenericContextStore>(cc: S) {
get: () => get(key),
})

function init<K2 extends keyof Required<S>[K]>(key2: K2, getter: () => Required<Required<S>[K]>[K2]): Required<Required<S>[K]>[K2] {
function init<K2 extends keyof Required<T>[K]>(key2: K2, getter: () => Required<Required<T>[K]>[K2]): Required<Required<T>[K]>[K2] {
if (hasNested(key2)) return getNested(key2)
return setNested(key2, getter())
}

function hook<K2 extends keyof Required<S>[K]>(key2: K2) {
function hook<K2 extends keyof Required<T>[K]>(key2: K2) {
const obj = {
value: null as Required<S>[K][K2],
value: null as Required<T>[K][K2],
isDefined: null as unknown as boolean,
}
attachHook(obj, {
set: v => setNested(key2, v as S[K][K2]),
set: v => setNested(key2, v as T[K][K2]),
get: () => getNested(key2),
})
attachHook(obj, {
Expand All @@ -93,20 +93,20 @@ function _getCtxHelpers<S extends TGenericContextStore>(cc: S) {
return obj
}

function setNested<K2 extends keyof Required<S>[K]>(key2: K2, v: Required<S[K]>[K2]) {
function setNested<K2 extends keyof Required<T>[K]>(key2: K2, v: Required<T[K]>[K2]) {
if (typeof obj.value === 'undefined') {
obj.value = {} as S[K]
obj.value = {} as T[K]
}
obj.value[key2] = v
return v
}
function delNested<K2 extends keyof Required<S>[K]>(key2: K2) {
setNested(key2, undefined as Required<S[K]>[K2])
function delNested<K2 extends keyof Required<T>[K]>(key2: K2) {
setNested(key2, undefined as Required<T[K]>[K2])
}
function getNested<K2 extends keyof Required<S>[K]>(key2: K2) { return (obj.value || {} as S[K])[key2] as Required<S>[K][K2] }
function hasNested<K2 extends keyof Required<S>[K]>(key2: K2) { return typeof (obj.value || {} as S[K])[key2] !== 'undefined' }
function getNested<K2 extends keyof Required<T>[K]>(key2: K2) { return (obj.value || {} as T[K])[key2] as Required<T>[K][K2] }
function hasNested<K2 extends keyof Required<T>[K]>(key2: K2) { return typeof (obj.value || {} as T[K])[key2] !== 'undefined' }
function entries() { return Object.entries((obj.value || {})) }
function clear() { obj.value = {} as S[K] }
function clear() { obj.value = {} as T[K] }

return obj
}
Expand All @@ -116,29 +116,29 @@ function _getCtxHelpers<S extends TGenericContextStore>(cc: S) {
*
* @returns whole context object
*/
function getCtx() { return cc }
function getCtx(): typeof cc { return cc }

/**
* Get value of event store property
*
* @param key property name
* @returns value of property by name
*/
function get<K extends keyof S>(key: K) { return getCtx()[key] }
function get<K extends keyof T>(key: K) { return getCtx()[key] }

/**
* Set value of event store property
*
* @param key property name
* @param v property value
*/
function set<K extends keyof S>(key: K, v: S[K]) {
function set<K extends keyof T>(key: K, v: T[K]) {
(getCtx())[key] = v
}

return {
getCtx,
restoreCtx: () => currentContext = cc,
restoreCtx: () => currentContext = cc as TGenericContextStore,
clearCtx: () => cc === currentContext ? currentContext = null : null,
store,
getStore: get,
Expand Down
1 change: 1 addition & 0 deletions packages/event-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export interface TGenericEvent {
id?: string
}

export interface TEmpty {}
8 changes: 4 additions & 4 deletions packages/event-http/src/event-http.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { TEventOptions, createEventContext, useEventContext } from '@wooksjs/event-core'
import { TEmpty, TEventOptions, createEventContext, useEventContext } from '@wooksjs/event-core'
import { THttpContextStore, THttpEventData } from './types'

export function createHttpContext(data: THttpEventData, options: TEventOptions) {
return createEventContext<THttpContextStore>({
return createEventContext<THttpContextStore, THttpEventData>({
event: {
...data,
type: 'HTTP',
Expand All @@ -11,6 +11,6 @@ export function createHttpContext(data: THttpEventData, options: TEventOptions)
})
}

export function useHttpContext<T extends object>() {
return useEventContext<THttpContextStore & T>('HTTP')
export function useHttpContext<T extends TEmpty>() {
return useEventContext<THttpContextStore & T, THttpEventData>('HTTP')
}
5 changes: 2 additions & 3 deletions packages/event-http/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { IncomingMessage, ServerResponse } from 'http'
import { TGenericEvent, TGenericContextStore } from '@wooksjs/event-core'
import { TTimeMultiString } from './utils/time'
import { EHttpStatusCode } from './utils/status-codes'
import { WooksURLSearchParams } from './utils/url-search-params'
Expand All @@ -9,11 +8,11 @@ export interface THttpEventData {
res: ServerResponse
}

export interface THttpEvent extends TGenericEvent, THttpEventData {
export interface THttpEvent {
type: 'HTTP'
}

export interface THttpContextStore extends TGenericContextStore<THttpEvent> {
export interface THttpContextStore {
searchParams?: TSearchParamsCache
cookies?: { [name: string]: string | null }
setCookies?: { [name: string]: TSetCookieData }
Expand Down
4 changes: 2 additions & 2 deletions scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ async function build(target) {

if (extractorResult.succeeded) {
out.success(`✅ API Extractor completed successfully.`)
await fs.rm(`${pkgDir}/dist/packages`, { recursive: true, force: true })
await fs.rm(`${pkgDir}/dist/common`, { recursive: true, force: true })
} else {
out.error(
`API Extractor completed with ${extractorResult.errorCount} errors` +
Expand All @@ -98,7 +100,5 @@ async function build(target) {
out.error(e.message)
}

await fs.rm(`${pkgDir}/dist/packages`, { recursive: true, force: true })
await fs.rm(`${pkgDir}/dist/common`, { recursive: true, force: true })
}
}

0 comments on commit 713c665

Please sign in to comment.