0

My overall goal is to get all jobs associated with a user.

This is my routing code in routes.ts

Route.get('/job/:homeowner_id?', 'JobsController.index')

This is my JobsController.index code inside JobsController

public async index({params, response}: HttpContextContract) {
    // If homeowner_id is passed in
    if (params) {
      const jobs = await Job
      .query()
      .select('id', 'status', 'contractor_id', 'address', 'homeowner_id', 'fence_material', 'fence_drawing_data', 'created_at', 'updated_at')
      .where('homeowner_id', params.homeowner_id)
       const index = {'total':jobs.length, 'jobs':jobs}
       return response.status(200).json(index)

    }
    // To return ALL jobs in database (probably won't be used)
    const jobs = await Job
    .query()
    .select('id', 'status', 'contractor_id', 'address', 'homeowner_id', 'fence_material', 'fence_drawing_data', 'created_at', 'updated_at')
    .orderBy('created_at', 'asc')

    const index = {'total':jobs.length, 'jobs':jobs}
    return response.status(200).json(index)
  }

Using Insomnia (Postman alternative), when I try to send a GET request to:

  • http://localhost:3333/job
  • http://localhost:3333/job?homeowner_id=1

both of these return the error:

    "message": "\".where\" expects value to be defined, but undefined is passed",
    "stack": "Exception: \".where\" expects value to be defined, but undefined is passed\n    at ModelQueryBuilder.validateWhereSingleArgument...

What is needing to be changed here in order for the optional parameter to work and lack of parameter to work?

1
  • You can always send query parameters. Parameter is inside url. So your route would be /job/1 or just /job. Deconstruct {params} in controller from context Commented Mar 13, 2022 at 5:46

1 Answer 1

0

You've messed up query parameters and params, it should be:

public async index({params, response}: HttpContextContract) {
    // If homeowner_id is passed in
    if (params.homeowner_id) {
      // Do you job if homeowner ID is exist

    }
    
    // Otherwise return all
  }

And send request with param or without:

  • http://localhost:3333/job
  • http://localhost:3333/job/1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.