prisma-korea / prisma-offset-pagination

Offset Pagination based on cursor system
46 stars 13 forks source link

FIX: Cursor Id validation #11

Closed guicuton closed 11 months ago

guicuton commented 1 year ago

This fix is related to issue: https://github.com/prisma-korea/prisma-offset-pagination/issues/9

When your table does not have a sequential primary key (like my case that is UUID), the decryptedCursor inside of a parseInt() always results into a number excepting the first page.

Sample with parseInt():

const cursors = ['c2FsdHlzYWx0YjhlZTZhMjMtNjcxYi00MTAxLThkMzgtYzFkZmNkZWM5ZDRk', 'c2FsdHlzYWx0NmJkMDk0YTQtYmY2Zi00YTg1LThlNDItOWNlYTYyNjlhYTI0', 'c2FsdHlzYWx0NzBlN2Q1NTgtZjY5MS00OTEyLTk3ZGItOTI5NDkyYzQwMzhi', 'c2FsdHlzYWx0MjU1ZTcwODYtNmQ0Yy00OWYyLWFjYTctYTYxYjljMTNkZGVj'];

cursors.forEach((cursor) => {
    const decryptedCursor = Buffer.from(cursor, 'base64').toString('ascii').slice(9);
    console.log(parseInt(decryptedCursor))
});
// output: NaN | 6 | 70 | 255
// All these should console as NaN

This behaviour leads to a falsy FALSE condition giving the idOrigin variable the NaN value resulting the error:

Argument id: Got invalid value NaN on prisma.model. Provided Float, expected String.

Instead of using the parseInt(decryptedCursor) we need use the Number(decryptedCursor) on ternary condition

Sample with Number():

const cursors = ['c2FsdHlzYWx0YjhlZTZhMjMtNjcxYi00MTAxLThkMzgtYzFkZmNkZWM5ZDRk', 'c2FsdHlzYWx0NmJkMDk0YTQtYmY2Zi00YTg1LThlNDItOWNlYTYyNjlhYTI0', 'c2FsdHlzYWx0NzBlN2Q1NTgtZjY5MS00OTEyLTk3ZGItOTI5NDkyYzQwMzhi', 'c2FsdHlzYWx0MjU1ZTcwODYtNmQ0Yy00OWYyLWFjYTctYTYxYjljMTNkZGVj', 
'c2FsdHlzYWx0Mg==', //Here is a encrypted cursor from a table with sequential id
'c2FsdHlzYWx0MjM3', //Here is a encrypted cursor from a table with sequential id
'c2FsdHlzYWx0MjMy' //Here is a encrypted cursor from a table with sequential id
];  

cursors.forEach((cursor) => {
    const decryptedCursor = Buffer.from(cursor, 'base64').toString('ascii').slice(9);
    console.log(Number(decryptedCursor))
});
// output: NaN | NaN | NaN | NaN | 2 | 237 | 232
guicuton commented 1 year ago

This PR also add the select. Related to issue: https://github.com/prisma-korea/prisma-offset-pagination/issues/8