Skip to content
Nuxt module to merge and transform API calls into a single file, like a payload extractor
JavaScript Vue
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci CHORE: Merge with nuxt default template for modules. Dec 6, 2019
.github CHORE: Added Github folder. Dec 6, 2019
.vscode fix: eslint config Dec 17, 2019
docs chore: updated github pages Jan 8, 2020
example feat: generate folder for github pages Dec 9, 2019
lib feat: better error report Dec 10, 2019
test
.browserslistrc FIX: Initial commit. Dec 6, 2019
.editorconfig CHORE: Merge with nuxt default template for modules. Dec 6, 2019
.eslintignore chore: tested with the generate Dec 9, 2019
.eslintrc.js chore: updated rulez of linting Jan 8, 2020
.gitignore chore: added apis-to-file Dec 7, 2019
.markdownlint.ignore chore: rulez for .md Dec 7, 2019
.markdownlint.json CHORE: Initial commit. Dec 6, 2019
.prettierignore FIX: Initial commit. Dec 6, 2019
.prettierrc FIX: Initial commit. Dec 6, 2019
.travis.yml FIX: Initial commit. Dec 6, 2019
CHANGELOG.md chore(release): 1.0.1 Jan 8, 2020
LICENSE CHORE: Merge with nuxt default template for modules. Dec 6, 2019
README.md docs: typo error Dec 9, 2019
_config.yml CHORE: Merge with nuxt default template for modules. Dec 6, 2019
babel.config.js CHORE: Initial commit. Dec 6, 2019
commitlint.config.js
husky.config.js CHORE: Initial commit. Dec 6, 2019
jest.config.js CHORE: Initial commit. Dec 6, 2019
package.json chore: updated scripts Jan 8, 2020
renovate.json CHORE: Merge with nuxt default template for modules. Dec 6, 2019
vue.config.js chore: updated vue config Jan 8, 2020
yarn.lock chore: updated dev dep Jan 8, 2020

README.md

🎉 Nuxt APIs to file

npm version npm downloads Circle CI Codecov License

Nuxt module to merge and transform API calls into a single file, like a payload-extractor.

💘 Motivation

If you have (like me), too much dispatch in you nuxtServerInit action, maybe you prefer to merge all of this requests into a single JSON file to speed up, blazing fast your nuxt-website! This file is generated during the build-process and it's called only once. In this way, your are also saving and protecting your data because you aren't exposing the .json file in the static/ dir (you can change this behavior passing a different configuration to the module).

Usually, when you call one or more API 📞, you're slowing down your website because every single request need to resolve the response (with different TTFB).

Having 3/4 requests in the nuxtServerInit or in the asyncData can increase up to a second the TTFB of your website (causing worse performance audits).

With this module you (and your users) no longer have to wait for this anymore, because everything is resolved during the build-process.

You can use this module for every static, shared or pre-loaded data.

Inspired by this comment.


Setup

  1. Add @luxdamore/nuxt-apis-to-file dependency to your project;
  2. Add @luxdamore/nuxt-apis-to-file to the buildModules section of your nuxt.config.js;
  3. Add the folder apis-to-json/ to your .gitignore file.
    yarn add @luxdamore/nuxt-apis-to-file # or npm install --save @luxdamore/nuxt-apis-to-file
    // nuxt.config.js
    export default {

        // Module installation
        modules: [ '@luxdamore/nuxt-apis-to-file' ], // nuxt < v2.9
        buildModules: [ '@luxdamore/nuxt-apis-to-file' ], // nuxt >= v2.9

        // Module config
        apisToFile: {
            file: {
                // The name of the file
                name: 'data',
                // The extension of the file
                ext: 'json',
                // The main folder where to save the generated file, you should add this path to your `.gitignore` file
                path: 'apis-to-file',
                // The `file.path` is always starting from the `srcDir`, but you can force it to the `static/` dir changing this
                startFromStaticDir: false,
                // Options passed directly to the `outputJson` method of the `fs-extra` library
                options: {},
            },
            // Hide console messages
            hideErrorsInConsole: false,
            hideGenericMessagesInConsole: false, // default = `! nuxtConfig.dev`
            // A sub-folder of `file.path` in which to place the file
            dir: null,
            // `@nuxtjs/axios` config is automatically injected, but you can override it here
            axios: {},
            // Your APIs to extract
            requests: [
                // Every request is passed to an `axios.create` instance
                {
                    endpoint: 'https://awesome-api.com/give-me-my-blazing-fast-data', // default = `axios.url`
                    method: 'get', // default = `axios.method || 'get'`
                    // The params of the request, you can pass a graph-ql query too, check it in the example folder
                    body: {},
                    // Use this to map the response in a custom `key`
                    field: 'categories', // default = `the actual index in this array of requests`
                    // Usually, your data is always nested in one or more objects
                    pathToData: 'data.categories.listCategories',
                    // In case of no-response, what value do you prefer for your empty data?
                    emptyValue: [],
                    // Like headers, authentication or everything is required by this request
                    config: {},
                },
            ],
        },

    };
    # In this example the *response* is:
    `response: {
        data: {
            categories: {
                listCategories: [ DATA ],
            },
        },
    }`,

    # but the extracted file is only containing the chosen *pathToData* in the *field* key:
    `{ categories: [ DATA ] }`

Usage

    // store/index.js
    export const actions = {
        async nuxtServerInit(
            { dispatch },
        ) {

            // usual old-slowly-way
            await dispatch(
                'items/getItemsCategories',  // TTFB + ~200ms
            );
            await dispatch(
                'news/getNewsCategories',  // TTFB + ~250ms
            );

            // with apis-to-json
            await dispatch(
                'build-data/getDataFromFile',
            );

        },
    };

    // create a module to load the generated file
    // store/build-data.js
    const getFile = () => import(
        '~/apis-to-file/data.json'
    ).then(
        m => m.default || m
    );

    export const actions = {
        async getDataFromFile(
            { commit }
        ) {

            let itemsCategories = []
                , newsCategories = []
            ;

            try {

                const { categories, otherCategories } = await getFile();

                if( categories )
                    itemsCategories = categories;

                if( otherCategories )
                    newsCategories = otherCategories;

            } catch( e ) {

                console.error(
                    {
                        e,
                    }
                );

            }

            commit(
                'items/SET_ITEMS_CATEGORIES',
                itemsCategories,
                {
                    root: true,
                }
            );

            commit(
                'news/SET_NEWS_CATEGORIES',
                newsCategories,
                {
                    root: true,
                }
            );

        }
    };

Related things you should know

Development

  1. Clone this repository;
  2. Install dependencies using yarn install or npm install;
  3. Start development server using npm run dev.

🐞 Issues

Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guidelines may be closed immediately.

👥 Contribution

Please make sure to read the Contributing Guide before making a pull request.

📖 Changelog

Details changes for each release are documented in the release notes.

📃 License

MIT License // Copyright (©) 2019-present Luca Iaconelli

💸 Are you feeling generous today? :)

Do you want to share a beer? We can be good friends.. Paypal // Patreon

It's always a good day to be magnanimous - cit

💼 Hire me

Otechie

ko-fi


✔ TODO

Just asking myself if i should do more.

  • Add more tests.
  • Automatically transform .gql and .graphql files for the json-body?
  • API calls should continue on error? (Instead of using a try-for i can use a for-try)
  • Add a plugin or a template for the generated data?
  • Automatically inject the data in context?
  • Automatically inject it in the store?
You can’t perform that action at this time.