Packer (#172)
* introduce pako and add general packer interface * add tests for packer * use function API instead of class API for better tree shaking support * refcatoring the rollup bundle config
This commit is contained in:
10
src/packer/base.ts
Normal file
10
src/packer/base.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { eventWithTime } from '../types';
|
||||
|
||||
export type PackFn = (event: eventWithTime) => string;
|
||||
export type UnpackFn = (raw: string) => eventWithTime;
|
||||
|
||||
export type eventWithTimeAndPacker = eventWithTime & {
|
||||
v: string;
|
||||
};
|
||||
|
||||
export const MARK = 'v1';
|
||||
2
src/packer/index.ts
Normal file
2
src/packer/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { pack } from './pack';
|
||||
export { unpack } from './unpack';
|
||||
10
src/packer/pack.ts
Normal file
10
src/packer/pack.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { deflate } from 'pako/dist/pako_deflate';
|
||||
import { PackFn, MARK, eventWithTimeAndPacker } from './base';
|
||||
|
||||
export const pack: PackFn = (event) => {
|
||||
const _e: eventWithTimeAndPacker = {
|
||||
...event,
|
||||
v: MARK,
|
||||
};
|
||||
return deflate(JSON.stringify(_e), { to: 'string' });
|
||||
};
|
||||
31
src/packer/unpack.ts
Normal file
31
src/packer/unpack.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { inflate } from 'pako/dist/pako_inflate';
|
||||
import { UnpackFn, eventWithTimeAndPacker, MARK } from './base';
|
||||
import { eventWithTime } from '../types';
|
||||
|
||||
export const unpack: UnpackFn = (raw: string) => {
|
||||
if (typeof raw !== 'string') {
|
||||
return raw;
|
||||
}
|
||||
try {
|
||||
const e: eventWithTime = JSON.parse(raw);
|
||||
if (e.timestamp) {
|
||||
return e;
|
||||
}
|
||||
} catch (error) {
|
||||
// ignore and continue
|
||||
}
|
||||
try {
|
||||
const e: eventWithTimeAndPacker = JSON.parse(
|
||||
inflate(raw, { to: 'string' }),
|
||||
);
|
||||
if (e.v === MARK) {
|
||||
return e;
|
||||
}
|
||||
throw new Error(
|
||||
`These events were packed with packer ${e.v} which is incompatible with current packer ${MARK}.`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error('Unknown data format.');
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user