Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS file download using API endpoint #2

Open
igorbumba opened this issue Apr 20, 2023 · 1 comment
Open

JS file download using API endpoint #2

igorbumba opened this issue Apr 20, 2023 · 1 comment
Assignees
Labels
documentation Improvements or additions to documentation

Comments

@igorbumba
Copy link
Collaborator

import { AxiosError } from 'axios';
import { NextApiRequest, NextApiResponse } from 'next';
import instance from '@libs/wordpress';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    if (req.method === 'POST') {
        try {
            const { data, status } = await instance.post('/download-route', { ids: req.body });
            const { data: file } = await instance.get(data.url, { responseType: 'arraybuffer' });
            res.setHeader('Content-Type', data.contentType);
            res.setHeader('Filename', data.basename);
            return res.status(status).send(file);
        } catch (e) {
            const err = e as AxiosError;
            const status = err?.response?.data?.statusCode || 400;
            return res.status(status).json({ ...err?.response?.data });
        }
    } else {
        return res.status(400).json({ message: 'Bad request!' });
    }
};

export default handler;
@igorbumba igorbumba added the documentation Improvements or additions to documentation label Apr 20, 2023
@igorbumba igorbumba self-assigned this Apr 20, 2023
@igorbumba
Copy link
Collaborator Author

import { useCallback, useState } from 'react';
import axios from 'axios';
import fileDownload from 'js-file-download';
import routes from '@libs/routes';

const useFileDownload = () => {
    const [downloading, setDownloading] = useState<boolean>(false);

    const downloadFiles = useCallback(
        files => {
            setDownloading(true);
            axios
                .post(routes.api.download, files, { responseType: 'blob' })
                .then(results => {
                    const file = new Blob([results.data]);
                    fileDownload(file, results.headers.filename);
                })
                .finally(() => setDownloading(false));
        },
        [setDownloading]
    );

    return {
        downloading,
        downloadFiles,
    };
};

export default useFileDownload;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant