Skip to content
Permalink
Browse files

feat: zipSharedUtil

  • Loading branch information...
kirillgroshkov committed Feb 9, 2019
1 parent 862ef74 commit 7d84a14d64a0c30f61426090b8962edb51832515
Showing with 56 additions and 0 deletions.
  1. +2 −0 src/index.ts
  2. +24 −0 src/util/zip.shared.util.test.ts
  3. +30 −0 src/util/zip.shared.util.ts
@@ -3,6 +3,7 @@ import { getDebug } from './util/debug'
import { localDateUtil, LUXON_ISO_DATE_FORMAT } from './util/localDate.util'
import { localTimeUtil } from './util/localTime.util'
import { processSharedUtil } from './util/process.shared.util'
import { zipSharedUtil } from './util/zip.shared.util'
import { ExtendedJoi, Joi } from './validation/joi/joi.extensions'
import {
anyObjectSchema,
@@ -61,4 +62,5 @@ export {
utcOffsetSchema,
ipAddressSchema,
processSharedUtil,
zipSharedUtil,
}
@@ -0,0 +1,24 @@
import { zipSharedUtil } from './zip.shared.util'

test('zip/unzip', async () => {
const s = 'abcd1234$%^'

// String
let zippedBuf = await zipSharedUtil.zipString(s)
const unzippedStr = await zipSharedUtil.unzipToString(zippedBuf)
expect(unzippedStr).toBe(s)

const sBuf = Buffer.from(s)
zippedBuf = await zipSharedUtil.zip(sBuf)
const unzippedBuf = await zipSharedUtil.unzip(zippedBuf)
expect(unzippedBuf).toEqual(sBuf)
})

test('compatible with java impl', async () => {
const s = 'aa'
const zippedBuf = await zipSharedUtil.zipString(s)
const bytes: number[] = []
zippedBuf.forEach(c => bytes.push(c))
// console.log(bytes)
expect(bytes).toEqual([120, 156, 75, 76, 4, 0, 1, 37, 0, 195])
})
@@ -0,0 +1,30 @@
import { promisify } from 'util'
import { ZlibOptions } from 'zlib'
import * as zlib from 'zlib'

const deflate = promisify(zlib.deflate.bind(zlib)) as Function
const inflate = promisify(zlib.inflate.bind(zlib)) as Function

class ZipSharedUtil {
// string > zip
async zip (buf: Buffer, options: ZlibOptions = {}): Promise<Buffer> {
return deflate(buf, options)
}

// zip > buffer
async unzip (buf: Buffer, options: ZlibOptions = {}): Promise<Buffer> {
return inflate(buf, options)
}

// convenience
async zipString (s: string, options?: ZlibOptions): Promise<Buffer> {
return this.zip(Buffer.from(s), options)
}

// convenience
async unzipToString (buf: Buffer, options?: ZlibOptions): Promise<string> {
return (await this.unzip(buf, options)).toString()
}
}

export const zipSharedUtil = new ZipSharedUtil()

0 comments on commit 7d84a14

Please sign in to comment.
You can’t perform that action at this time.