I recently embarked on a new project using the adonisjs framework. I had the option to utilize expressjs, but I was drawn to adonisjs due to its structured nature, especially reminiscent of Laravel.
My current challenge revolves around building a RESTful API and understanding the underlying concepts of routing, middleware, and utilizing an apiController (a custom controller designed to manage all api requests).
Here is a snippet of what I have implemented so far:
routes.js
Route.post('api/v1/login', 'ApiController.login')
Route.post('api/v1/register', 'ApiController.register')
// API Routes
Route.group('api', function() {
Route.get('users', 'ApiController.getUsers')
}).prefix('/api/v1').middlewares(['auth:api'])
ApiController.js
'use strict'
const User = use('App/Model/User')
const Validator = use('Validator')
const FAIL = 0
const SUCCESS = 1
class ApiController {
* login (request, response) {
let jsonResponse = {}
const email = request.input('email')
const password = request.input('password')
// validate form input
const rules = {
email: 'required|email',
password: 'required'
}
const messages = {
'email.required': 'Email field is required.',
'password.required': 'Password field is required.'
}
const validation = yield Validator.validateAll(request.all(), rules, messages)
if (validation.fails()) {
jsonResponse.status = FAIL
jsonResponse.response = {}
jsonResponse.response.message = validation.messages()[0].message
} else {
try {
yield request.auth.attempt(email, password)
const user = yield User.findBy('email', email)
const token = yield request.auth.generate(user)
jsonResponse.status = SUCCESS
jsonResponse.response = {}
jsonResponse.response.message = "Logged In Successfully"
jsonResponse.response.user = user
jsonResponse.response.token = token
} catch (e) {
jsonResponse.status = FAIL
jsonResponse.response = {}
jsonResponse.response.message = e.message
}
}
return response.json(jsonResponse)
}
}
module.exports = ApiController
config/auth.js
'use strict'
const Config = use('Config')
module.exports = {
/*
|--------------------------------------------------------------------------
| Authenticator
|--------------------------------------------------------------------------
|
| Authenticator is a combination of HTTP Authentication scheme and the
| serializer to be used for retrieving users. Below is the default
| authenticator to be used for every request.
|
| Available Schemes - basic, session, jwt, api
| Available Serializers - Lucid, Database
|
*/
authenticator: 'session',
// Additional configurations...
config/shield.js
// Shield configurations...Encountering an issue when hitting the login web service via Postman where the user is validated, but an exception occurs at
const token = request.auth.generate(user)
with the error message request.auth.generate is not a function
.
If anyone has encountered this before or can provide insights, your help would be greatly appreciated.
Thank you!