How do I create a async-function timeout error handler as a hook in feathers that resides in the service file to handle promises in hooks?
Post created specifically as suggested by @Bergi on my previous question
If you are looking to implement a generic async-function timeout (for promises failing to fulfill for whatever reason) as a featherjs hook, you might want to ask a new (different!) question about specifically that.
I need a function that would be added to the database.hooks.js file (like the errorhandler in the example docs) that would handle exceptions (that cause timeouts) caused by hooks similar to get-database-by-id.js without changing the code in get-database-by-id.js:
get-database-by-id.js
const errors = require('@feathersjs/errors');
module.exports = function (options = {}) {
return async context => {
let promise = new Promise((resolve,reject) => {
context.app.service('database').find({
query: {"id":context.data.id}
}).then(result => {
resolve(result.data[0].data)
// console: error: Unhandled Rejection at: Promise
//browser: hangs
});
});
let result = await promise;
if (result) {
return context;
}
};
};
database.hooks.js (with example errorhandler from docs, does not work with promises)
const { authenticate } = require('@feathersjs/authentication').hooks;
const getDatabaseById = require('../../hooks/get-database-by-id');
const errors = require('@feathersjs/errors');
const errorHandler = ctx => {
if (ctx.error) {
const error = ctx.error;
if (!error.code) {
const newError = new errors.GeneralError("server error");
ctx.error = newError;
return ctx;
}
if (error.code === 404 || process.env.NODE_ENV === "production") {
error.stack = null;
}
return ctx;
}
};
module.exports = {
before: {
all: [ authenticate('jwt')],
find: [],
get: [],
create: [
getDatabaseById,
],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [errorHandler],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};