* 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:
yz-yu
2020-04-07 18:03:47 +08:00
committed by GitHub
parent 18129bab70
commit 4f36d0e57d
23 changed files with 316 additions and 218 deletions

10
src/packer/base.ts Normal file
View 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
View File

@@ -0,0 +1,2 @@
export { pack } from './pack';
export { unpack } from './unpack';

10
src/packer/pack.ts Normal file
View 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
View 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.');
}
};