From 3ea3d273a573c4a1a80f4be0b4a40e912e319f96 Mon Sep 17 00:00:00 2001 From: Trevor Buckner Date: Sun, 5 Jan 2020 23:48:50 -0500 Subject: [PATCH] Add zlib compression to the "text" field. Now, when a file is saved, the original text field is blanked out and the "compressed" binary version is saved instead. Viewing files in Edit page unzips and views them just fine. Does not compress old files unless they are opened and resaved by someone. Have not tested on the "share" or "print" pages yet, but should work. --- server/homebrew.api.js | 4 ++++ server/homebrew.model.js | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/server/homebrew.api.js b/server/homebrew.api.js index c8c0e9122..acb57c68a 100644 --- a/server/homebrew.api.js +++ b/server/homebrew.api.js @@ -1,6 +1,7 @@ const _ = require('lodash'); const HomebrewModel = require('./homebrew.model.js').model; const router = require('express').Router(); +const zlib = require('zlib'); // const getTopBrews = (cb)=>{ // HomebrewModel.find().sort({ views: -1 }).limit(5).exec(function(err, brews) { @@ -47,6 +48,9 @@ router.put('/api/update/:id', (req, res)=>{ HomebrewModel.get({ editId: req.params.id }) .then((brew)=>{ brew = _.merge(brew, req.body); + brew.textBin = zlib.deflateSync(req.body.text); // Compress brew text to binary before saving + brew.text = ''; // Clear out the non-binary text field so its not saved twice + brew.updatedAt = new Date(); if(req.account) brew.authors = _.uniq(_.concat(brew.authors, req.account.username)); diff --git a/server/homebrew.model.js b/server/homebrew.model.js index 587ca37c1..b9cf00319 100644 --- a/server/homebrew.model.js +++ b/server/homebrew.model.js @@ -1,12 +1,14 @@ const mongoose = require('mongoose'); const shortid = require('shortid'); const _ = require('lodash'); +const zlib = require('zlib'); const HomebrewSchema = mongoose.Schema({ shareId : { type: String, default: shortid.generate, index: { unique: true } }, editId : { type: String, default: shortid.generate, index: { unique: true } }, title : { type: String, default: '' }, text : { type: String, default: '' }, + textBin : { type: Buffer }, description : { type: String, default: '' }, tags : { type: String, default: '' }, @@ -51,6 +53,10 @@ HomebrewSchema.statics.get = function(query){ return new Promise((resolve, reject)=>{ Homebrew.find(query, (err, brews)=>{ if(err || !brews.length) return reject('Can not find brew'); + if(!_.isUndefined(brews[0].textBin)) { // Uncompress zipped text field + unzipped = zlib.unzipSync(brews[0].textBin); + brews[0].text = unzipped.toString(); + } return resolve(brews[0]); }); });