@navios/core 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
- import type { FastifyInstance } from 'fastify'
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
2
2
  import type { ZodTypeProvider } from 'fastify-type-provider-zod'
3
3
 
4
- import type { ModuleMetadata } from '../metadata/index.mjs'
4
+ import { NaviosException } from '@navios/common'
5
+
6
+ import type { EndpointMetadata, ModuleMetadata } from '../metadata/index.mjs'
5
7
  import type { ClassType } from '../service-locator/index.mjs'
6
8
 
7
- import { HttpException } from '../exceptions/index.mjs'
8
9
  import { Logger } from '../logger/index.mjs'
9
- import { extractControllerMetadata } from '../metadata/index.mjs'
10
+ import { EndpointType, extractControllerMetadata } from '../metadata/index.mjs'
10
11
  import {
11
12
  getServiceLocator,
12
13
  inject,
@@ -31,9 +32,9 @@ export class ControllerAdapterService {
31
32
  ): void {
32
33
  const controllerMetadata = extractControllerMetadata(controller)
33
34
  for (const endpoint of controllerMetadata.endpoints) {
34
- const { classMethod, url, httpMethod, config } = endpoint
35
+ const { classMethod, url, httpMethod } = endpoint
35
36
 
36
- if (!url || !config) {
37
+ if (!url) {
37
38
  throw new Error(
38
39
  `[Navios] Malformed Endpoint ${controller.name}:${classMethod}`,
39
40
  )
@@ -43,47 +44,24 @@ export class ControllerAdapterService {
43
44
  controllerMetadata,
44
45
  endpoint,
45
46
  )
46
- const guards = this.guardRunner.makeContext(executionContext)
47
- const { querySchema, requestSchema, responseSchema } = config
48
- const schema: Record<string, any> = {}
49
- if (querySchema) {
50
- schema.querystring = querySchema
51
- }
52
- if (requestSchema) {
53
- schema.body = requestSchema
54
- }
55
- if (responseSchema) {
56
- schema.response = {
57
- 200: responseSchema,
58
- }
59
- }
60
47
  instance.withTypeProvider<ZodTypeProvider>().route({
61
48
  method: httpMethod,
62
49
  url: url.replaceAll('$', ':'),
63
- schema,
64
- preHandler: async (request, reply) => {
65
- if (guards.size > 0) {
66
- getServiceLocator().registerInstance(Request, request)
67
- getServiceLocator().registerInstance(Reply, reply)
68
- getServiceLocator().registerInstance(
69
- ExecutionContextToken,
70
- executionContext,
71
- )
72
- executionContext.provideRequest(request)
73
- executionContext.provideReply(reply)
74
- const canActivate = await this.guardRunner.runGuards(
75
- guards,
76
- executionContext,
77
- )
78
- getServiceLocator().removeInstance(Request)
79
- getServiceLocator().removeInstance(Reply)
80
- getServiceLocator().removeInstance(ExecutionContextToken)
81
- if (!canActivate) {
82
- return reply
83
- }
84
- }
85
- },
86
- handler: async (request, reply) => {
50
+ schema: this.provideSchemaForConfig(endpoint),
51
+ preHandler: this.providePreHandler(executionContext),
52
+ handler: this.provideHandler(controller, executionContext, endpoint),
53
+ })
54
+
55
+ this.logger.debug(
56
+ `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`,
57
+ )
58
+ }
59
+ }
60
+
61
+ providePreHandler(executionContext: ExecutionContext) {
62
+ const guards = this.guardRunner.makeContext(executionContext)
63
+ return guards.size > 0
64
+ ? async (request: FastifyRequest, reply: FastifyReply) => {
87
65
  getServiceLocator().registerInstance(Request, request)
88
66
  getServiceLocator().registerInstance(Reply, reply)
89
67
  getServiceLocator().registerInstance(
@@ -92,41 +70,108 @@ export class ControllerAdapterService {
92
70
  )
93
71
  executionContext.provideRequest(request)
94
72
  executionContext.provideReply(reply)
95
- const controllerInstance = await inject(controller)
73
+ let canActivate = true
96
74
  try {
97
- const { query, params, body } = request
98
- const argument: Record<string, any> = {}
99
- if (query && Object.keys(query).length > 0) {
100
- argument.params = query
101
- }
102
- if (params && Object.keys(params).length > 0) {
103
- argument.urlParams = params
104
- }
105
- if (body) {
106
- argument.data = body
107
- }
108
- const result = await controllerInstance[classMethod](argument)
109
- reply.status(200).send(result)
110
- } catch (error) {
111
- if (error instanceof HttpException) {
112
- reply.status(error.statusCode).send(error.response)
113
- } else {
114
- reply.status(500).send({
115
- message: 'Internal server error',
116
- error: (error as Error).message,
117
- })
118
- }
75
+ canActivate = await this.guardRunner.runGuards(
76
+ guards,
77
+ executionContext,
78
+ )
119
79
  } finally {
120
80
  getServiceLocator().removeInstance(Request)
121
81
  getServiceLocator().removeInstance(Reply)
122
82
  getServiceLocator().removeInstance(ExecutionContextToken)
123
83
  }
124
- },
125
- })
84
+ if (!canActivate) {
85
+ return reply
86
+ }
87
+ }
88
+ : undefined
89
+ }
126
90
 
127
- this.logger.debug(
128
- `Registered ${httpMethod} ${url} for ${controller.name}:${classMethod}`,
91
+ private provideSchemaForConfig(endpointMetadata: EndpointMetadata) {
92
+ if (!endpointMetadata.config) {
93
+ this.logger.warn(`No config found for endpoint ${endpointMetadata.url}`)
94
+ return {}
95
+ }
96
+ const { querySchema, requestSchema, responseSchema } =
97
+ endpointMetadata.config
98
+ const schema: Record<string, any> = {}
99
+ if (querySchema) {
100
+ schema.querystring = querySchema
101
+ }
102
+ if (requestSchema) {
103
+ schema.body = requestSchema
104
+ }
105
+ if (responseSchema) {
106
+ schema.response = {
107
+ 200: responseSchema,
108
+ }
109
+ }
110
+
111
+ return schema
112
+ }
113
+
114
+ private provideHandler(
115
+ controller: ClassType,
116
+ executionContext: ExecutionContext,
117
+ endpointMetadata: EndpointMetadata,
118
+ ): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
119
+ switch (endpointMetadata.type) {
120
+ case EndpointType.Unknown:
121
+ this.logger.error(
122
+ `Unknown endpoint type ${endpointMetadata.type} for ${controller.name}:${endpointMetadata.classMethod}`,
123
+ )
124
+ throw new NaviosException('Unknown endpoint type')
125
+ case EndpointType.Config:
126
+ return this.provideHandlerForConfig(
127
+ controller,
128
+ executionContext,
129
+ endpointMetadata,
130
+ )
131
+ case EndpointType.Handler:
132
+ this.logger.error('Not implemented yet')
133
+ throw new NaviosException('Not implemented yet')
134
+ }
135
+ }
136
+
137
+ private provideHandlerForConfig(
138
+ controller: ClassType,
139
+ executionContext: ExecutionContext,
140
+ endpointMetadata: EndpointMetadata,
141
+ ): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {
142
+ return async (request, reply) => {
143
+ getServiceLocator().registerInstance(Request, request)
144
+ getServiceLocator().registerInstance(Reply, reply)
145
+ getServiceLocator().registerInstance(
146
+ ExecutionContextToken,
147
+ executionContext,
129
148
  )
149
+ executionContext.provideRequest(request)
150
+ executionContext.provideReply(reply)
151
+ const controllerInstance = await inject(controller)
152
+ try {
153
+ const { query, params, body } = request
154
+ const argument: Record<string, any> = {}
155
+ if (query && Object.keys(query).length > 0) {
156
+ argument.params = query
157
+ }
158
+ if (params && Object.keys(params).length > 0) {
159
+ argument.urlParams = params
160
+ }
161
+ if (body) {
162
+ argument.data = body
163
+ }
164
+ const result =
165
+ await controllerInstance[endpointMetadata.classMethod](argument)
166
+ reply
167
+ .status(endpointMetadata.successStatusCode)
168
+ .headers(endpointMetadata.headers)
169
+ .send(result)
170
+ } finally {
171
+ getServiceLocator().removeInstance(Request)
172
+ getServiceLocator().removeInstance(Reply)
173
+ getServiceLocator().removeInstance(ExecutionContextToken)
174
+ }
130
175
  }
131
176
  }
132
177
  }