I am trying to figure out a better way to organize my codebase (my Services). Right now I have a folder for my Services and a class (like AuthService.ts) and inside I have my methods (example: registerUser, loginUser).
I was plannning to do something like this:
// AuthService/registerUser.ts
class RegisterUser {
public async handler (userData: UserData) {
// code to register user
return user
}
}
export default new RegisterUser().handler
// ./AuthService/loginUser.ts
class LoginUser {
public async handler (userData: UserCredentials) {
// code to login user
return {user, token}
}
}
export default new LoginUser().handler
// ./AuthService/index.ts
import loginUser from './loginUser'
import registerUser from './registerUser'
export default {loginUser, registerUser}
// Controller
import AuthService from 'App/Services/AuthService'
export default class SessionsController {
public async register ({ request }: HttpContextContract) {
const { name, email, password } = request.post()
const user = await AuthService.registerUser({ name, email, password })
if (!user) {
console.log('failed!?')
}
return { user }
}
}
I separated all my methods in new classes. I made an index.ts
file to make easier to export all those methods (don't break my old implementation), but I could just import the specific method I need instead of all the services.
This is write on AdonisJS v5, but the real doubt is about structure, import/export, and architecture.
Is there anything wrong with this approach? What should be the right way to better organize a Service with a lot of methods? (This is an example, actually there are 4 more methods.. and a few to come...)
Aucun commentaire:
Enregistrer un commentaire