From 4b2397d68b62d9f5682d1fd9f4fb2082ac4aa260 Mon Sep 17 00:00:00 2001
From: eug-vs <eug-vs@keemail.me>
Date: Wed, 12 Aug 2020 18:42:29 +0300
Subject: feat: impelemnt fetchImages hook

---
 hooks/fetchImages.ts | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
 create mode 100644 hooks/fetchImages.ts

(limited to 'hooks/fetchImages.ts')

diff --git a/hooks/fetchImages.ts b/hooks/fetchImages.ts
new file mode 100644
index 0000000..d6e7d27
--- /dev/null
+++ b/hooks/fetchImages.ts
@@ -0,0 +1,25 @@
+import { HookContext } from '@feathersjs/feathers';
+import Bluebird from 'bluebird';
+import _ from 'lodash';
+
+
+export default (paths: string[]) => async (context: HookContext): Promise<HookContext> => {
+  const { service, app, result, params: { user } } = context;
+  const fileService = app.service('files');
+  const model = service.Model;
+
+  Bluebird.map(paths, async (path: string) => {
+    const url = _.get(result, path);
+
+    // If image is not from our s3, fetch it!
+    if (!fileService.isS3url(url)) {
+      const filePath = await fileService.downloadFile(url);
+      const s3Path = fileService.generateS3Path(user?.username);
+      const s3Url = await fileService.uploadFileToS3(filePath, s3Path);
+      return model.findOneAndUpdate({ _id: result._id }, { [path]: s3Url });
+    }
+    return url;
+  });
+  return context;
+};
+
-- 
cgit v1.2.3