Service repository is a pattern to separate business logic and query logic. This package is designed to help simplify the maintenance of large and medium scale applications.
node ace add @adityadarma/adonis-service-repository
node ace make:service ServiceName
If you want to change the core service according to your wishes without changing the existing methods, you can publish it first.
node ace service:publish
construct(protected serviceName: Service) {}
async data()
{
// Get data
const result = await this.userService.methodName()
return result.getData()
// OR
return (await this.userService.methodName()).getData()
}
async jsonResponse({ response }: HttpContext)
{
const result = await this.userService.methodName()
return result.getApiResponse()
// OR
return response.status(result.getCode()).json(result.getApiResponse())
}
// Set resource on controller
async withResource({ response }: HttpContext)
{
const result = await this.userService.methodName()
return await result.setResource(ResourceName)
// OR
return response.status(result.getCode()).json((await result.setResource(UserResource)).getApiResponse())
// OR
return response.status(result.getCode()).json((await result.setResource(UserResource)).withoutCode().getApiResponse())
}
Every all exception, must have handle to class ServiceException
async methodName()
{
try {
.........
if (false) {
throw new ServiceException('Error exception');
}
..........
return this.setMessage('Message data')
.setCode(200)
.setData(data)
// OR
return this.setMessage('Message data')
.setCode(200)
.setData(data)
.setResource(ClassResource) // if you want set resource in service
.setPaginateCase('snakeCase') // if you want change key pagination case
} catch (error) {
return this.exceptionResponse(error)
}
}
node ace make:repository nameRepository
construct(protected repositoryName: Repository) {}
async methodName()
{
this.repositoryName.functionName();
}
node ace make:resource nameResource
async methodName()
{
try {
.........
if (false) {
throw new ServiceException('Error exception');
}
..........
return this.setMessage('Message data')
.setCode(200)
.setData(data)
.setResource(ClassResource)
} catch (error) {
return this.exceptionResponse(error);
}
}
This package is open-sourced software licensed under the MIT license.