-
Notifications
You must be signed in to change notification settings - Fork 5
Translate ID
Translate ID is a useful function to allow you to customise how the findOne query generates an ID for the MongoDB query. For example, a standard query would look something like this: GET https://awesomeapp.com/v1/project/5894b7285a608f0842674a0e
whereas you might want to expose a different kind of ID than the Mongo ObjectID on the public API: GET https://awesomeapp.com/v1/project/8a1643ea-8d4e-4bd4-88e8-6f36aba5ea5a
As long as you know how to translate the request ID (8a1643ea-8d4e-4bd4-88e8-6f36aba5ea5a) into the actual Object ID (5894b7285a608f0842674a0e) using just the request ID and the request object (i.e. express request object) then you can use translateId()
to convert the request ID to the Object ID.
module.exports.autoroute = autorouteJson({
translateId(id, req) {
// id - request id
// req - express request
// return the value of the Object Id or a promise that resolves to the Object Id
return id;
}
});
One common use case when working with Authmaker is the ability to get details for the currently logged in user, such as their name, email etc. When you have initialised the application and authorised you may not yet know your current user's ID, so you wouldn't be able to make the query GET https://awesomeapp.com/v1/users/5894b7285a608f0842674a0f
to get your details because you don't know that 5894b7285a608f0842674a0f is your logged in user's ID
One way around that is to allow the end user to query their user with a key of me
like this: GET https://awesomeapp.com/v1/users/me
. You then translate the id from me
to the ObjectId of the current logged in user.
Here is an example route:
const authmakerVerifyExpress = require('authmaker-verify-express');
const authmakerCommon = require('@authmaker/common');
const autorouteJSON = require('express-autoroute-json');
module.exports.autoroute = autorouteJSON({
model: authmakerCommon.models.user,
authentication: authmakerVerifyExpress.mongo(),
attributes: [
'email',
'displayName',
],
translateId(id, req) {
if (id === 'me') {
return req.user.id;
}
return id;
},
find: {
authorisation(req) {
return {
userId: req.user.id,
};
},
},
});