Pārlūkot izejas kodu

call api to get pdf info

RoyLiu 5 gadi atpakaļ
vecāks
revīzija
abe4b9aaeb
4 mainītis faili ar 96 papildinājumiem un 31 dzēšanām
  1. 11 6
      apis/index.ts
  2. 4 0
      constants/apiPath.ts
  3. 47 25
      containers/PdfViewer.tsx
  4. 34 0
      helpers/apiHelpers.ts

+ 11 - 6
apis/index.ts

@@ -1,8 +1,13 @@
-import 'isomorphic-unfetch';
+import invokeApi from '../helpers/apiHelpers';
 
-const getInfo: {} = async () => {
-  const res = await fetch('https://api.github.com/repos/zeit/next.js');
-  return res.json();
-};
+import apiPath from '../constants/apiPath';
 
-export default getInfo;
+export const initialPdfFile = async (token: string): Promise<any> => invokeApi({
+  path: apiPath.initPdf,
+  method: 'GET',
+  data: {
+    f: token,
+  },
+});
+
+export default {};

+ 4 - 0
constants/apiPath.ts

@@ -0,0 +1,4 @@
+export default {
+  initPdf: '/api/v1/init',
+  getOriginalPdfFile: '/api/v1/original.pdf',
+};

+ 47 - 25
containers/PdfViewer.tsx

@@ -1,5 +1,11 @@
-import React, { useEffect, useState, useRef, useCallback } from 'react';
+import React, {
+  useEffect, useState, useRef, useCallback,
+} from 'react';
+import queryString from 'query-string';
+import config from '../config';
+import apiPath from '../constants/apiPath';
 
+import { initialPdfFile } from '../apis';
 import Viewer from '../components/Viewer';
 import { fetchPdf } from '../helpers/pdf';
 import { watchScroll } from '../helpers/utility';
@@ -11,37 +17,53 @@ import useStore from '../store';
 const PdfViewer: React.FunctionComponent = () => {
   const containerRef = useRef<HTMLDivElement>(null);
   const pageRef = useRef(1);
-  const viewportRef = useRef({height: 0, width: 0});
+  const viewportRef = useRef({ height: 0, width: 0 });
   const [initialized, setInitialize] = useState(false);
-  const [{totalPage, currentPage, viewport, pdf, scale, rotation}, dispatch] = useStore();
-  const { setTotalPage, setCurrentPage, setPdf, setProgress, setViewport } = useActions(dispatch);
+  const [{
+    totalPage, currentPage, viewport, pdf, scale, rotation,
+  }, dispatch] = useStore();
+  const {
+    setTotalPage, setCurrentPage, setPdf, setProgress, setViewport,
+  } = useActions(dispatch);
 
-  const pdfGenerator = async () => {
-    const pdf = await fetchPdf('../static/Quick Start Guide.pdf', getProgress);
+  const setLoadingProgress = (totalSize: number) => (progress: ProgressType): void => {
+    setProgress({
+      total: totalSize,
+      loaded: progress.loaded,
+    });
+  };
 
-    const totalNum = pdf.numPages;
-    setTotalPage(totalNum);
-    setPdf(pdf);
+  const getViewport = async (pdfEle: any, s: number): Promise<any> => {
+    const page = await pdfEle.getPage(1);
+    const iViewport = page.getViewport({ scale: s });
 
-    await getViewport(pdf, 1);
-    setInitialize(true);
-  }
+    iViewport.width = Math.round(iViewport.width);
+    iViewport.height = Math.round(iViewport.height);
+    setViewport(iViewport);
+  };
 
-  const getViewport = async (pdfEle: any, scale: number) => {
-    const page = await pdfEle.getPage(1);
-    const viewport = page.getViewport({ scale });
-    viewport.width = Math.round(viewport.width);
-    viewport.height = Math.round(viewport.height);
-    setViewport(viewport);
-  }
-
-  const getProgress = useCallback((progress: ProgressType) => {
-    setProgress(progress);
-  }, [dispatch]);
+  const pdfGenerator = async (): Promise<any> => {
+    const parsed = queryString.parse(window.location.search);
+    const res = await initialPdfFile(parsed.token as string);
+
+    if (res.data) {
+      const iPdf = await fetchPdf(
+        `${config.API_HOST}${apiPath.getOriginalPdfFile}?transaction_id=${res.data.transaction_id}`,
+        setLoadingProgress(res.data.size),
+      );
+
+      const totalNum = iPdf.numPages;
+      setTotalPage(totalNum);
+      setPdf(iPdf);
+
+      await getViewport(iPdf, 1);
+      setInitialize(true);
+    }
+  };
 
   const scrollUpdate = useCallback((state: ScrollStateType) => {
-    const viewport = viewportRef.current;
-    const page = Math.round((state.lastY + viewport.height / 1.4) / (viewport.height + 50));
+    const iViewport = viewportRef.current;
+    const page = Math.round((state.lastY + iViewport.height / 1.4) / (iViewport.height + 50));
     if (page !== pageRef.current) {
       setCurrentPage(page);
     }

+ 34 - 0
helpers/apiHelpers.ts

@@ -0,0 +1,34 @@
+import fetch from 'isomorphic-unfetch';
+import queryString from 'query-string';
+import config from '../config';
+
+type Props = {
+  path: string;
+  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+  data: Record<string, any>;
+};
+
+export default ({ path, method, data }: Props): Promise<any> => {
+  let stringified = '';
+  const options: any = {
+    method,
+    headers: {
+      Accept: 'application/json',
+      'Content-type': 'application/json',
+    },
+  };
+
+  if (data) {
+    if (method === 'GET') {
+      stringified = queryString.stringify(data);
+    } else {
+      options.body = JSON.stringify(data);
+    }
+  }
+
+  const apiHost = config.API_HOST;
+
+  return fetch(`${apiHost}${path}?${stringified}`, options)
+    .then(res => res.json())
+    .catch(error => ({ error: true, message: error.message }));
+};