Skip to content

Commit 03c1420

Browse files
committed
feat(mongo-pagination) use base62Fast for token encode/decode
1 parent 9e05ae5 commit 03c1420

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed

packages/mongo-pagination/src/Token.ts

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ import {
33
createExtension,
44
defineStructure,
55
} from '@andrew_l/tl-pack';
6-
import { crc32 } from '@andrew_l/toolkit';
6+
import { base62Fast, crc32 } from '@andrew_l/toolkit';
77
import { ObjectId } from 'mongodb';
88

9-
const SCHEMA_VERSION = 1;
109
const OBJECT_ID_TOKEN = 100;
1110

1211
const extensions = [
@@ -54,6 +53,7 @@ export interface TokenOptions {
5453
const TokenStructure = defineStructure({
5554
name: 'PaginationToken',
5655
version: 1,
56+
checksum: true,
5757
properties: {
5858
modelNameCrc: { type: CORE_TYPES.Int32, required: true },
5959
keys: { type: [String], required: true },
@@ -102,13 +102,13 @@ export class Token {
102102
* Retrieves the string representation of token.
103103
*/
104104
public stringify(): string {
105-
return this.buffer().toString('base64url');
105+
return base62Fast.encode(this.buffer());
106106
}
107107

108108
/**
109109
* Retrieves binary buffer representation of token.
110110
*/
111-
public buffer(): Buffer {
111+
public buffer(): Uint8Array {
112112
const struct = new TokenStructure({
113113
modelNameCrc: this.modelNameCRC,
114114
sortDirection: Object.values(this.sortDirection),
@@ -117,30 +117,32 @@ export class Token {
117117
payload: this.payload,
118118
});
119119

120-
return Buffer.from(struct.toBuffer({ extensions }));
120+
return struct.toBuffer({ extensions });
121121
}
122122

123123
/**
124124
* Encode token from provided value
125125
*/
126-
static from(value: string | Buffer): Token {
127-
const buffer = Buffer.isBuffer(value)
128-
? value
129-
: Buffer.from(value, 'base64url');
126+
static from(value: string | Buffer | Uint8Array): Token {
127+
const buffer =
128+
Buffer.isBuffer(value) || value instanceof Uint8Array
129+
? value
130+
: base62Fast.decode(value);
130131

131132
const struct = TokenStructure.fromBuffer(buffer);
132133

133134
const token = new Token();
134135

135136
token.modelNameCRC = struct.modelNameCrc;
136-
token.sortDirection = Object.fromEntries(
137-
struct.keys.map((key, idx) => [key, struct.sortDirection[idx]]),
138-
);
139-
token.sortValues = Object.fromEntries(
140-
struct.keys.map((key, idx) => [key, struct.sortValues[idx]]),
141-
);
137+
token.sortDirection = {};
138+
token.sortValues = {};
142139
token.payload = struct.payload ?? {};
143140

141+
for (let idx = 0; idx < struct.keys.length; idx++) {
142+
token.sortValues[struct.keys[idx]] = struct.sortValues[idx];
143+
token.sortDirection[struct.keys[idx]] = struct.sortDirection[idx];
144+
}
145+
144146
return token;
145147
}
146148
}

0 commit comments

Comments
 (0)