Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/plugin-router-hapi/src/attach.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export default function attachRouter(service: Microfleet, config: RouterHapiPlug
name: 'microfleetRouter',
version: '1.0.0',
async register(server: Server) {
for (const [actionName, handler] of service.router.routes.get(ActionTransport.http).entries()) {
const routes = service.router.routes.get<{ TransportOptions: { hapi: ServerRoute } }>(ActionTransport.http)
for (const [actionName, handler] of routes.entries()) {
const path = fromNameToPath(actionName, config.prefix)
const serverRoute: ServerRoute = {
path,
Expand Down
6 changes: 5 additions & 1 deletion packages/plugin-router/__tests__/artifacts/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const reqPromise = async (reqUrl: URL, requestOptions: any) => {
return res
}

export function getHTTPRequest<T = any>(_options: RequestInit & {url: string }): (action: string, params?: any, opts?: any) => Bluebird<T> {
export function getHTTPRequest<T = any>(_options: RequestInit & { url: string }): (action: string, params?: any, opts?: any) => Bluebird<T> {
return (action: string, params?: any, opts: any = {}): Bluebird<T> => {
const { url, ...options } = _options
const requestOptions = {
Expand All @@ -70,6 +70,10 @@ export function getHTTPRequest<T = any>(_options: RequestInit & {url: string }):
...options,
}

if (opts.method) {
requestOptions.method = opts.method
}

const reqUrl = new URL(`${url}${action}`)

requestOptions.body = (params || opts.json) ? JSON.stringify(opts.json || params) : null
Expand Down
16 changes: 7 additions & 9 deletions packages/plugin-router/__tests__/suites/01.router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,13 @@ describe('@microfleet/plugin-router', async () => {
}

await service.connect()
await Promise.all([
rget({ sample: 1, bool: true }),
rget({ sample: 'crap', bool: true }, false),
rget({ sample: 13, bool: 'invalid' }, false),
rget({ sample: 13, bool: '0' }),
rget({ sample: 13, bool: '0', oops: 'q' }, false),
rget({ sample: 13.4, bool: '0' }, false),
rget(null, false, { json: { sample: 13.4, bool: '0' }, method: 'post' }),
])
await rget({ sample: 1, bool: true })
await rget({ sample: 'crap', bool: true }, false)
await rget({ sample: 13, bool: 'invalid' }, false)
await rget({ sample: 13, bool: '0' })
await rget({ sample: 13, bool: '0', oops: 'q' }, false)
await rget({ sample: 13.4, bool: '0' }, false)
await rget(null, false, { json: { sample: 13.4, bool: '0' }, method: 'post' })
})

it('should be able to set schema and responseSchema from action name', async () => {
Expand Down
15 changes: 9 additions & 6 deletions packages/plugin-router/src/extensions/audit/log.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Microfleet } from '@microfleet/core-types'
import type { ServiceRequest } from '../../types/router'
import type { ReplyGenericInterface, RequestGenericInterface, ServiceRequest } from '../../types/router'
import { Lifecycle, LifecycleExtensions } from '../../lifecycle/index'
import { initTimingExtension } from './timing'

Expand All @@ -13,15 +13,18 @@ export type AuditLogExtensionParams = {
getErrorLevel?: (this: Microfleet, error: any) => ErrorLevel | undefined
}

export type MetaLog = {
headers: Record<string, unknown>
export type MetaLog<
DefaultRequest extends RequestGenericInterface = RequestGenericInterface,
DefaultReply extends ReplyGenericInterface = ReplyGenericInterface
> = {
headers: DefaultRequest["Headers"]
latency: number | null
method: string
params: any
query: any
params: DefaultRequest["Params"]
query: DefaultRequest["Querystring"]
route: string
transport: string
response?: any
response?: DefaultReply["Reply"]
err?: Error
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { parse } from 'qs'
import { parse, type ParsedQs } from 'qs'
import { Lifecycle } from '../../lifecycle/index'
import { ServiceRequest } from '../../types/router'

type QSParserAugmentedAction = ServiceRequest & {
action: ServiceRequest['action'] & {
transformQuery?: (...args: any[]) => any;
transformOpts?: any;
transformQuery?: (input: Record<string, any>) => ParsedQs;
transformOpts?: Parameters<typeof parse>[1];
};
}

Expand All @@ -19,7 +19,8 @@ async function preValidate(request: QSParserAugmentedAction): Promise<any> {
const { action } = request
const { transformQuery = identity, transformOpts } = action

request.query = transformQuery(parse(query, {
// module actually handles all variations of input
request.query = transformQuery(parse(query as any, {
depth: 1,
parameterLimit: 10,
parseArrays: false,
Expand Down
3 changes: 2 additions & 1 deletion packages/plugin-router/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export type {
ServiceMiddleware,
ServiceActionHandler,
ServiceActionAuthGetName,
TransportOptions,
RequestGenericInterface,
ReplyGenericInterface
} from './types/router'

export type { AuthInfo } from './lifecycle/handlers/auth'
14 changes: 10 additions & 4 deletions packages/plugin-router/src/routes.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { ServiceAction } from './types/router'
import type { ReplyGenericInterface, RequestGenericInterface, ServiceAction } from './types/router'

export type RouteName = string
export type TransportName = string
export type RoutesCollection = Map<RouteName, ServiceAction>
export type RoutesCollection<
DefaultRequest extends RequestGenericInterface = RequestGenericInterface,
DefaultResponse extends ReplyGenericInterface = ReplyGenericInterface
> = Map<RouteName, ServiceAction<DefaultRequest, DefaultResponse>>
export type RoutesGroupedByTransport = Map<TransportName, RoutesCollection>
export default class Routes {
protected groupedByTransport: RoutesGroupedByTransport = new Map()

get(transport: TransportName): RoutesCollection {
get<
DefaultRequest extends RequestGenericInterface = RequestGenericInterface,
DefaultResponse extends ReplyGenericInterface = ReplyGenericInterface
>(transport: TransportName): RoutesCollection<DefaultRequest, DefaultResponse> {
const { groupedByTransport } = this
const routes: RoutesCollection = groupedByTransport.get(transport) || new Map()
const routes: RoutesCollection<DefaultRequest, DefaultResponse> = groupedByTransport.get(transport) || new Map()

groupedByTransport.set(transport, routes)

Expand Down
44 changes: 30 additions & 14 deletions packages/plugin-router/src/types/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,50 @@ export type ServiceMiddleware = (this: Microfleet, request: ServiceRequest) => P
export type ServiceActionAuthGetName = (request: ServiceRequest) => string
export type ServiceActionHandler = ServiceAction['handler']

export interface ServiceAction<R = unknown> {
handler(this: Microfleet, request: ServiceRequest, ...params: any[]): Promise<R>

export interface RequestGenericInterface {
Params?: unknown;
Headers?: unknown;
Querystring?: unknown;
Locals?: unknown;
TransportOptions?: unknown;
}

export interface ReplyGenericInterface {
Reply?: unknown;
}
export interface ServiceAction<
DefaultRequest extends RequestGenericInterface = RequestGenericInterface,
DefaultReply extends ReplyGenericInterface = ReplyGenericInterface,
> {
handler(this: Microfleet, request: ServiceRequest, ...params: any[]): Promise<DefaultReply["Reply"]>
actionName: string
transports: ServiceRequest['transport'][]
transportOptions?: TransportOptions
transportOptions?: DefaultRequest["TransportOptions"]
validateResponse: boolean
schema?: string | null | boolean
responseSchema?: string;
readonly?: boolean
}

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TransportOptions {}

export interface ServiceRequest<R = unknown> {
export interface ServiceRequest<
DefaultRequest extends RequestGenericInterface = RequestGenericInterface,
DefaultReply extends ReplyGenericInterface = ReplyGenericInterface,
ErrorArg extends Error & { name: string, code?: string } = any
> {
route: string
action: ServiceAction<R>
params: any
headers: any
query: any
action: ServiceAction<DefaultRequest, DefaultReply>
params: DefaultRequest["Params"]
headers: DefaultRequest["Headers"]
query: DefaultRequest["Querystring"]
method: keyof typeof RequestDataKey
transport: typeof ActionTransport[keyof typeof ActionTransport]
transportRequest: any | ClientRequest
locals: any
locals: DefaultRequest["Locals"]
parentSpan: null
span: null
log: Logger
response?: unknown
error?: any
response?: DefaultReply["Reply"]
error?: ErrorArg
reformatError: boolean
}