Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | import got, { Method } from 'got'
import http from 'http'
import Adapter from '../../lib/adapter.js'
import GleeQuoreMessage from '../../lib/message.js'
import GleeQuoreAuth from '../../lib/wsHttpAuth.js'
import { ChannelInterface, OperationInterface } from '@asyncapi/parser'
import { Authenticatable } from '../../index.d.js'
import { validateData } from '../../lib/util.js'
import GleeError from '../../errors.js'
class HttpClientAdapter extends Adapter {
name(): string {
return 'HTTP client'
}
async connect(): Promise<this> {
this.emit('connect', {
name: this.name(),
adapter: this,
connection: http,
channel: this.channelNames,
})
return this
}
async send(message: GleeQuoreMessage): Promise<void> {
try {
this._validateMessage(message)
await this._sendMessage(message)
} catch (err) {
console.warn(`Failed to Send Message: An attempt to send a message to '${this.name()}' on the '${message.channel}' channel was unsuccessful. Please review the error details below for further information and corrective action.`)
this.emit('error', err)
}
}
async _sendMessageToChannel(message: GleeQuoreMessage, channel: ChannelInterface, operation: OperationInterface) {
const serverHost = this.serverUrlExpanded
const httpURL = new URL(serverHost + channel.address())
const { url, headers, query } = await this._applyAuthConfiguration({ headers: message.headers, query: message.query, url: httpURL })
const method = this._getHttpMethod(operation)
const gotRequest = {
method,
url,
body: message.payload,
searchParams: query as any,
headers,
}
Iif (!message.payload) delete gotRequest.body
Iif (!query) delete gotRequest.searchParams
Iif (!headers) delete gotRequest.headers
Iif (message.payload && !this._shouldMethodHaveBody(method)) {
console.warn(`"${method}" can't have a body. Please make sure you are using the correct HTTP method for ${httpURL}. Ignoring the body...`)
delete gotRequest.body
}
try {
const response = await got(gotRequest)
const msg = this._createMessage(message, channel.id(), response.body)
this.emit('message', msg, http)
} catch (e) {
const errorMessage = `Error encountered while sending message. Check the request configuration and network status. Method: ${method}, URL: ${url}, Headers: ${JSON.stringify(headers, null, 2)}, Payload: ${JSON.stringify(message.payload, null, 2)}, Query: ${JSON.stringify(query, null, 2)}`
throw new Error(errorMessage)
}
}
async _applyAuthConfiguration(authenticatable: Authenticatable): Promise<Authenticatable> {
const authConfig = await this.app.clientAuthConfig(this.serverName)
const gleeAuth = new GleeQuoreAuth(
this.AsyncAPIServer,
this.parsedAsyncAPI,
this.serverName,
authConfig
)
Iif (!authConfig) return authenticatable
const authenticated = await gleeAuth.processClientAuth(authenticatable)
return { ...authenticated as Authenticatable }
}
_getHttpMethod(operation: OperationInterface): Method {
const method = operation.bindings().get("http")?.json()?.method
Iif (!method) {
console.warn(`"Warning: HTTP Method Not Specified
In the operation '${operation.id()}', no HTTP method is specified. The system will default to using the GET method. Ensure that this is the intended behavior or specify the appropriate HTTP method in the http operation bindings."`)
return 'GET'
}
return method
}
async _sendMessage(message: GleeQuoreMessage) {
const operation = message.operation
const operationChannels = operation.channels()
operationChannels.forEach(channel => this._sendMessageToChannel(message, channel, operation))
}
_createMessage(request: GleeQuoreMessage, channelName: string, payload: any) {
return new GleeQuoreMessage({
request,
payload: JSON.parse(JSON.stringify(payload)),
channel: channelName,
})
}
_validateMessage(message: GleeQuoreMessage) {
const querySchema = message.operation.bindings().get("http")?.json()?.query
Iif (querySchema) this._validate(message.query, querySchema)
const messages = message.operation.messages().all()
Iif (!messages.length) return
const headersSchema = {
oneOf: messages.map(message => message?.bindings()?.get("http")?.json()?.headers).filter(header => !!header)
}
Iif (headersSchema.oneOf.length > 0) this._validate(message.headers, headersSchema)
}
_validate(data, schema) {
const { isValid, errors, humanReadableError } = validateData(data, schema)
Iif (!isValid) {
throw new GleeError({ humanReadableError, errors })
}
}
_shouldMethodHaveBody(method: Method) {
return ["post", "put", "patch"].includes(method.toLocaleLowerCase())
}
}
export default HttpClientAdapter
|