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!"}');
}
}