What is the best way to accomplish this using typescript/adonis?

While exploring some code examples on Bitbucket, I came across a sample that demonstrated how to paginate query results using JavaScript. However, as I attempted to apply it in my project, I encountered difficulties in declaring the types required for the operation.

The error message I'm currently facing is related to this line of code:

const pagination:TPagination = usersResults.toJSON()

The specific issue states that the type '{ meta: any; data: ModelObject[]; }' does not possess certain expected properties.

        ***Example Code***
          async index ({ view, params, request, response }) {
            const page = params.page || 1
            const search = request.input('search') || ''
            const employees = await Employee.query()
                                            .where('name', 'LIKE', '%' + search + '%')
                                            .paginate(page, 10)
            const pagination = employees.toJSON()
            pagination.route = 'employees.pagination'
            if(pagination.lastPage < page && page != 1) {
              response.route(pagination.route, { page: 1 }, null, true)
            }
            else {
              pagination.offset = (pagination.page - 1) * pagination.perPage
              pagination.search = search
              return view.render('employees.index', { employees: pagination })
            }
          }

        }
         ***My Attempted Code***
        public async searchByName ({request,params, response}: HttpContextContract) {   
                interface TPagination {
                    route: string;
                    lastPage: number;
                    offset:number;
                    search:string;
                    page:number;
                    perPage:number;
                    [key: string]: any;
                    meta: any;
                    data: ModelObject[];

                           
                } 
                try {
                    const page = params.page || 1
                    const search = request.input('search') || ''
                    const usersResults = await User.query()
                                                    .where('name', 'LIKE', '%' + search + '%')
                                                    .orWhere('cns','LIKE','%'+   search +'%')
                                                    .paginate(page, 10)
                    const pagination:TPagination = usersResults.toJSON()
                    pagination.route = 'pagination.users'
                    if(pagination.lastPage < page && page != 1) {
                        response.redirect().toRoute(pagination.route, { page: 1 })
                    }
                    else {
                      pagination.offset = (pagination.page - 1) * pagination.perPage
                      pagination.search = search
                    }

                } catch {
                    return response.status(400).json('{"error":"Usuário não encontrado!"}');
                }
            
            }   

Answer №1

Perhaps it's a little delayed, but keep this in mind for future use. The toJSON() function specifically returns a ModelObject type to allow for the addition or removal of different keys from the main object. This means that the result may not exactly match the original query object.

In your scenario, you can obtain the rows directly from the paginate object like so:

const pagination:TPagination = usersResults.all()

The all() method of the paginate will retrieve all objects on the current page, maintaining the correct typage.

I hope this clarifies things!

P.S. solution discovered at: https://github.com/adonisjs/lucid/blob/efed38908680cca3b288d9b2a123586fab155b1d/src/Database/Paginator/SimplePaginator.ts#L20

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

How can you incorporate a value into a variable in PHP?

Hey there! I'm pretty new to PHP and I've been working on building a program that resembles a spreadsheet. My form consists of columns and cells, allowing users to add or delete rows using Javascript. The challenge I'm facing is automating t ...

Creating new Angular2 Observables - Subscribing to undefined developments

Is it a scoping issue or a problem with how my observables are set up? Can you assist me in figuring it out? To explain my logic: My goal is to first check if the data is available locally before making an http.get request for it. I want to return the loc ...

typescript max recursion depth restricted to 9 levels

After countless attempts, I finally managed to create a generic type that provides me with all possible combinations of JSON key lists and values. Additionally, I have developed a method to limit the recursion within this type. type EditAction<T,P exten ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

Interactive Map Displayed within a Pop-up Window

Recently, I developed a custom Google map where points are plotted and an HTML popup window appears when the image is clicked. Now, my goal is to open a file with JavaScript functions inside a lightbox/fancybox when a user clicks on an image. Below is th ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

What is the best way to trigger the code within my useEffect React hook to execute again upon refreshing the page?

I'm encountering an issue where the value of states is becoming 'undefined' after refreshing the page. Within my useEffect hook, I am generating a random number to select a question object from an array. Everything works smoothly on the ini ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

The Express application seems to load forever after a certain period of time

I encountered a peculiar problem with my express application. It was deployed on the server and functioning properly, but after a few hours, when I tried to access the website again, it kept loading indefinitely. Below is my app.js code: const express = r ...

Angular 1 and Javascript offer a different approach than using lodash omit and the delete operator

I am facing an issue with a child component where I need to remove properties from an object. Normally, using Lodash, it should work with the following code snippet: this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSup ...

Set up a global variable for debugging

Looking to include and utilize the function below for debugging purposes: export function debug(string) { if(debugMode) { console.log(`DEBUG: ${string}`) } } However, I am unsure how to create a globally accessible variable like debugMode. Can this be ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Guidelines on navigating a blank page using the Nuxt-js method

I have run into an issue in my Nuxt.js project where I need to open a link in a new target when a user clicks a button. Despite trying various solutions, I haven't been able to find a workaround within the Nuxt.js framework itself. <a :href=&qu ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

interactive form fields updating using javascript

Hey there! I'm a beginner in web development and currently facing a challenge. I have a form with 2 fields generated by one drop-down menu. I've managed to generate one field, but struggling to get the other due to my limited knowledge. I just ne ...

The additional cost associated with using a React hook is called the "

Our system includes a theme context provider that passes down a theme to all child components, calculated based on the device's dimensions. We can easily access these values using the useTheme hook in any component. In addition, we have a constants f ...