From 02872836f2d2e7daea19c8f3898a14e7e2f71434 Mon Sep 17 00:00:00 2001 From: dotansimha Date: Tue, 24 Jan 2017 22:44:05 +0200 Subject: [PATCH] Step 12.12: Create pictures store --- imports/collections/pictures.ts | 43 +++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 imports/collections/pictures.ts diff --git a/imports/collections/pictures.ts b/imports/collections/pictures.ts new file mode 100644 index 0000000..cc86b92 --- /dev/null +++ b/imports/collections/pictures.ts @@ -0,0 +1,43 @@ +import { MongoObservable } from 'meteor-rxjs'; +import { UploadFS } from 'meteor/jalik:ufs'; +import { Meteor } from 'meteor/meteor'; +import { Picture, DEFAULT_PICTURE_URL } from '../models'; + +export interface PicturesCollection extends MongoObservable.Collection { + getPictureUrl(selector?: Object | string): string; +} + +export const Pictures = + new MongoObservable.Collection('pictures') as PicturesCollection; + +export const PicturesStore = new UploadFS.store.GridFS({ + collection: Pictures.collection, + name: 'pictures', + filter: new UploadFS.Filter({ + contentTypes: ['image/*'] + }), + permissions: new UploadFS.StorePermissions({ + insert: picturesPermissions, + update: picturesPermissions, + remove: picturesPermissions + }), + transformWrite(from, to) { + // The transformation function will only be invoked on the server. Accordingly, + // the 'sharp' library is a server-only library which will cause an error to be + // thrown when loaded on the global scope + const Sharp = Npm.require('sharp'); + // Compress picture to 75% from its original quality + const transform = Sharp().png({ quality: 75 }); + from.pipe(transform).pipe(to); + } +}); + +// Gets picture's url by a given selector +Pictures.getPictureUrl = function (selector) { + const picture = this.findOne(selector) || {}; + return picture.url || DEFAULT_PICTURE_URL; +}; + +function picturesPermissions(userId: string): boolean { + return Meteor.isServer || !!userId; +}