Browse Source

add utils

Yuki Takei 4 years ago
parent
commit
ef9135e726
2 changed files with 32 additions and 0 deletions
  1. 9 0
      packages/app/src/utils/axios.ts
  2. 23 0
      packages/app/src/utils/download.ts

+ 9 - 0
packages/app/src/utils/axios.ts

@@ -0,0 +1,9 @@
+// eslint-disable-next-line no-restricted-imports
+import axios from 'axios';
+
+export default axios.create({
+  headers: {
+    'X-Requested-With': 'XMLHttpRequest',
+    'Content-Type': 'application/json',
+  },
+});

+ 23 - 0
packages/app/src/utils/download.ts

@@ -0,0 +1,23 @@
+import path from 'path';
+import fs from 'graceful-fs';
+import mkdirp from 'mkdirp';
+import streamToPromise from 'stream-to-promise';
+import { Readable, Writable, Transform } from 'stream';
+import axios from '~/utils/axios';
+
+export async function downloadTo(url: string, outDir: string, fileName: string, transform: Transform|null = null): Promise<void> {
+  // get
+  const response = await axios.get(url, { responseType: 'stream' });
+  // mkdir -p
+  mkdirp.sync(outDir);
+
+  // replace and write
+  let stream: Readable = response.data;
+  if (transform != null) {
+    stream = stream.pipe(transform);
+  }
+  const file = path.join(outDir, fileName);
+  const writeStream: Writable = stream.pipe(fs.createWriteStream(file));
+
+  return streamToPromise(writeStream);
+}