Skip to content

Commit

Permalink
fix(mongo): support cursor pagination on Date properties
Browse files Browse the repository at this point in the history
Closes #5496
  • Loading branch information
B4nan committed May 5, 2024
1 parent 6683bcc commit 4281320
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/core/src/utils/Cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,13 @@ export class Cursor<
}

static decode(value: string): unknown[] {
return JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
return JSON.parse(Buffer.from(value, 'base64url').toString('utf8')).map((value: unknown) => {
if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}/)) {
return new Date(value);
}

return value;
});
}

static getDefinition<Entity extends object>(meta: EntityMetadata<Entity>, orderBy: OrderDefinition<Entity>) {
Expand Down
63 changes: 63 additions & 0 deletions tests/features/cursor-based-pagination/GH5478.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { ObjectId, MikroORM, Entity, PrimaryKey, Property } from '@mikro-orm/mongodb';

@Entity()
class EntityForFindByCursorTest {

@PrimaryKey()
_id!: ObjectId;

@Property()
myDate: Date;

@Property()
bar?: string;

constructor(myDate: Date) {
this.myDate = myDate;
this.bar = 'bar';
}

}

let orm: MikroORM;

beforeAll(async () => {
orm = MikroORM.initSync({
entities: [EntityForFindByCursorTest],
dbName: 'mikro-orm-test',
});
await orm.em.nativeDelete(EntityForFindByCursorTest, {});
});

afterAll(() => orm.close(true));

test('empty result with findByCursor and orderBy with Date', async () => {
orm.em.create(EntityForFindByCursorTest, { myDate: new Date('2020-01-01T00:00:00.000Z') });
orm.em.create(EntityForFindByCursorTest, { myDate: new Date('2020-01-02T00:00:00.000Z') });
orm.em.create(EntityForFindByCursorTest, { myDate: new Date('2020-01-03T00:00:00.000Z') });
orm.em.create(EntityForFindByCursorTest, { myDate: new Date('2020-01-04T00:00:00.000Z') });
orm.em.create(EntityForFindByCursorTest, { myDate: new Date('2020-01-05T00:00:00.000Z') });
await orm.em.flush();
orm.em.clear();

const all = await orm.em.findAll(EntityForFindByCursorTest);
expect(all.length).toBe(5);

const curOne = await orm.em.findByCursor(EntityForFindByCursorTest, {}, {
first: 3,
orderBy: { myDate: 'ASC' },
});

expect(curOne.length).toBe(3);

orm.em.clear();

const curTwo = await orm.em.findByCursor(EntityForFindByCursorTest, {}, {
first: 3,
after: curOne,
orderBy: { myDate: 'ASC' },
});

expect(curTwo.length).toBe(2);

});

0 comments on commit 4281320

Please sign in to comment.