Reputation: 1722
I'm using loopback3 and I'm thinking about optimising the codebase now, what is the point of injecting the application object as a parameter to getUser method from afterRemote hook https://loopback.io/doc/en/lb2/Remote-hooks.html, if I can access loopback instance by requiring it directly inside userService.ts.
I feel that I'm missing something important here, I tried to summarise below
A. For me importing is better since I will have less code and, there will be no need to inject the app each time.
B. Injected and Imported objects are equal, _.isEqual(app, App)
C. I've checked the performance with process.hrtime() and got same results.
app/models/activity.ts
import {UserService} from 'app/service/userService';
import {Attach} from 'app/models/remote/activityRemote';
export = function (Activity) {
Activity.afterRemote('find', function (ctx, result, next) {
UserService.getUser(Activity.app, Activity.username)
.then(() => next())
.catch(next);
});
/**
* attach remote
*/
Attach(Activity);
};
userService.ts
import {Server} from 'app/server/interface/server';
import * as App from 'app/server/server';
import * as _ from 'lodash';
/**
* @class UserService
*/
export class UserService {
/**
* get user's public profile
* @param {Server} app loopback app
* @param {string} username
* @returns {Promise<User>}
*/
public static getUser(app: Server, username: string): Promise<User> {
return App.models.user.findOne(filter) // Equal and
return app.models.user.findOne(filter) // does the same
.then((user: User) => {
if (!user) {
return Promise.reject(ServerError.get('User not found', 404));
}
return Promise.resolve(user);
});
}
}
server.ts
import {Server} from 'app/server/interface/server';
import * as loopback from 'loopback';
import * as boot from 'loopback-boot';
let App: Server = loopback();
module.exports = App;
export = App;
App.start = () => {
return App.listen(() => {
const baseUrl = App.get('url').replace(/\/$/, '');
App.emit('started');
console.log('Web server listening at: %s', baseUrl);
if (App.get('loopback-component-explorer')) {
console.log(
'Browse your REST API at %s%s',
baseUrl,
App.get('loopback-component-explorer').mountPath
);
}
});
};
boot(App, __dirname, (err: Error) => {
if (err) {
throw err;
}
if (require.main === module) {
App.start();
}
});
Upvotes: 0
Views: 194
Reputation: 30430
Unless you have multiple loopback applications in the same process going around, then you have no reason to pass the application as a parameter. Just import
the app as it's more readable and cleaner.
Also you don't need to use Promise.resolve
when you already have a promise:
return app.models.user.findOne(filter) // does the same
.then((user: User) => {
if (!user) {
throw ServerError.get('User not found', 404);
}
return user;
});
This will have the same effect.
Upvotes: 2