Bitwise
Bitwise

Reputation: 8461

Sending back custom JSON response with ajax request

I'm trying to send back user information from the backend to the frontend but I'm having a hard time understanding how this is supposed to be formatted.

CONTROLLLER

  def create
    user = User.new(user_params)

    if user.save
      auth_token = Knock::AuthToken.new(payload: { sub: user.id })
      created_user = {
        userEmail: user.email,
        userID:    user.id
      }

      respond_to do |format|
        format.json { render json: auth_token, created_user }
      end
    else
      respond_to do |format|
        format.json { render json: { errors: user.errors.full_messages }, status: :unprocessable_entity }
      end
    end
  end

The problem is in the success path. It's giving me this error when I try to run my test.

ERROR:

SyntaxError:
   /Users/Desktop/Work/ping-party/app/controllers/api/v1/users_controller.rb:23: syntax error, unexpected '}', expecting =>
   /Users/Desktop/Work/ping-party/app/controllers/api/v1/users_controller.rb:29: syntax error, unexpected keyword_end, expecting '}'
   /Users/Desktop/Work/ping-party/app/controllers/api/v1/users_controller.rb:37: syntax error, unexpected keyword_end, expecting '}'

TEST:

context "POST /v1/users" do
it "create a new user" do
  post '/api/v1/users',
    params: {
      user: {
        email: "[email protected]",
        password: "password123"
      }
    }

  res = JSON.parse(response.body)
  binding.pry
  expect(res).to include("jwt")
  expect(res).to include("user")
  expect(User.count).to eq(1)
end
end

It says there is a syntax error but for the life of me I can't see what I'm doing wrong. Can anyone help? Thank You.

Upvotes: 0

Views: 100

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

The problem is here:

render json: auth_token, created_user

The syntax is incorrect. Probably (according to your tests) you want something like:

render json: { user: created_user, jwt: auth_token.token)

More info.

Upvotes: 1

Necrogoru
Necrogoru

Reputation: 126

You can store auth_token and created_user in a hash:

auth_token = Knock::AuthToken.new(payload: { sub: user.id })
created_user = {
  userEmail: user.email,
  userID:    user.id
}
output = { auth_token: auth_token, created_user: created_user }

...

format.json { render json: output }

Then rails can render output like json.

Upvotes: 1

Related Questions