Skip to content

Commit

Permalink
feat: add better error message.
Browse files Browse the repository at this point in the history
  • Loading branch information
KhudaDad414 committed Oct 20, 2023
1 parent f0d7d84 commit 269a441
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions src/lib/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
import { pathToFileURL } from 'url'
import GleeError from '../errors/glee-error.js'
import { getParsedAsyncAPI } from './asyncapiFile.js'
import Debug from 'debug'
const debug = Debug('glee:functions')

interface FunctionInfo {
run: GleeFunction
Expand Down Expand Up @@ -53,30 +55,40 @@ const { GLEE_DIR, GLEE_FUNCTIONS_DIR } = getConfigs()
export const functions: Map<string, FunctionInfo> = new Map()

export async function register(dir: string) {
debug(`Attempting to register functions from directory: ${dir}`)
try {
const statsDir = await stat(dir)
if (!statsDir.isDirectory()) return
if (!statsDir.isDirectory()){
debug('Provided path is not a directory. Skipping.')
return
}
} catch (e) {
if (e.code === 'ENOENT') return
debug(`Error while checking directory: ${e}`)
throw e
}

try {
const files = await walkdir.async(dir, { return_object: true })
debug(`Found function files: ${Object.keys(files)}`)

return await Promise.all(
Object.keys(files).map(async (filePath) => {
try {
const functionName = basename(filePath, extname(filePath))
debug(`Registering function: ${functionName}`)

const { default: fn } = await import(pathToFileURL(filePath).href)
functions.set(functionName, {
run: fn,
})
} catch (e) {
debug(`Error while registering function:`)
console.error(e)
}
})
)
} catch (e) {
debug(`Error while walking directory:`)
console.error(e)
}
}
Expand All @@ -91,18 +103,26 @@ export async function trigger({
message: GleeMessage
}) {
try {
debug(`Triggering function for operation ID: ${operationId}`)
const parsedAsyncAPI = await getParsedAsyncAPI()

let res = await functions
.get(operationId)
.run(gleeMessageToFunctionEvent(message, app))
if (res === undefined) res = null
const operationFunction = functions.get(operationId)
if(!operationFunction){
const errMsg = `Failed to trigger function: No function registered for operation ID "${operationId}". please make sure you have a function named: "${operationId}(.js|.ts)" in your functions directory.`
logError(new Error(errMsg ), {
highlightedWords: [`"${operationId}"`],
})
return
}
let functionResult = await operationFunction.run(gleeMessageToFunctionEvent(message, app))
if (functionResult === undefined) functionResult = null
const { humanReadableError, errors, isValid } = validateData(
res,
functionResult,
FunctionReturnSchema
)

if (!isValid) {
debug(`Function ${operationId} returned invalid data.`)
const err = new GleeError({
humanReadableError,
errors,
Expand All @@ -116,7 +136,7 @@ export async function trigger({
return
}

res?.send?.forEach((msg) => {
functionResult?.send?.forEach((msg) => {
const localServerProtocols = ['ws', 'wss', 'http', 'https']
const serverProtocol = parsedAsyncAPI.servers().get(msg.server || message.serverName).protocol().toLocaleLowerCase()
const isBroadcast =
Expand All @@ -134,7 +154,7 @@ export async function trigger({
)
})

res?.reply?.forEach((msg) => {
functionResult?.reply?.forEach((msg) => {
message.reply({
payload: msg.payload,
headers: msg.headers,
Expand Down

0 comments on commit 269a441

Please sign in to comment.