How to return a specific status with Adonis.js/Node

Asked

Viewed 544 times

0

I am trying to return a specific status and a message in my api, I tried this way:

return response.status(409).json({message: 'User already registered'})

But I’m getting:

Response is not defined

I tried to import Sponse:

const response = use('Adonis/Src/Response')

But this way I get:

Sponse.status is not a Function

  • Put the entire method where that code is, please.

1 answer

1


Here I have an example of an HTTP controller made with Adonis, where I return different status and messages. From the description of your error, it seems that you are not receiving "Answer" as parameter.

"use strict";
const User = use("App/Models/User");
const Hash = use("Hash");
const moment = use("moment");

/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */

/**
 * Resourceful controller for interacting with sessions
 */
class SessionController {

  async store({ request, response, auth }) {
    const {
      email,
      password,
      origin,
      sistema,
      versao,
      api,
      marca
    } = request.all();
    try {
      const user = await User.findBy("email", email);
      if (!user) {
        return response
          .status(404)
          .json({ message: "O e-mail informado não foi localizado" });
      }

      const isSame = await Hash.verify(password, user.password);

      if (!isSame) {
        return response
          .status(401)
          .json({ message: "A senha ou o email informados estão incorretos" });
      }

      if (
        (origin === "MOBILE" && user.type === "ADMIN") ||
        (origin === "WEB" && user.type === "USUARIO")
      ) {
        return response
          .status(403)
          .send({ error: { message: "Usuário não autorizado" } });
      }
      const token = await auth.attempt(email, password);
      if (origin === "MOBILE") {
        const now = moment().format("YYYY-MM-DD HH:mm:ss");
        const dados_log = {
          user_id: user.id,
          sistema,
          versao,
          api,
          marca,
          created_at: now,
          updated_at: now
        };
        await use("Database")
          .table("logins")
          .insert(dados_log);
      }
      return response.status(200).send({ token, user });
    } catch (err) {
      return response.status(500).send({
        message:
          "Erro ao tentar logar o usuário. Verifique o login e a senha informados"
      });
    }
  }


}

module.exports = SessionController;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.