FeathersJS: Creating custom methods.

Omoike Sarah Igho
1 min readDec 21, 2017
feathersJs

A JavaScript method is a property containing a function definition.

It is actually better when your routes are unambiguous as much as possible.For instance: students/:studentId/posts is - nonetheless nice to read for humans - well not as easy to parse and process as the equivalent /posts?studentId=<studentid> which is already supportend by Feathers out of the box.In addition this can work efficiently if you are using Feathers via one of the transport meduim i.e websocket connections,this doesn't have any route concept.

However, nested routes for services can still be created by registering an existing service on the nested route and mapping the route parameter to a query parameter like this:

const crypto = require('crypto');

class PasswordService {
create(data) {
const studentId = data.student_id;
const studentService = this.app.service('student');

return studentService.patch(studentId, {
passwordToken: crypto.randomBytes(48)
}).then(student => sendEmail(student))
}

setup(app) {
this.app = app;
}
}
// For the new route, map the `:studentId` route parameter to the query in a hook
app.service('students/:studentId/posts').hooks({
before: {
find(hook) {
hook.params.query.studentId = hook.params.studentId;
},
create: mapStudentIdToData,
update: mapStudentIdToData,
patch: mapStudentIdToData
}
})

Now going to /users/123/posts will call postService.find({ query: { userId: 123 } }) and return all posts for that user.

--

--