npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@luxdamore/nuxt-apis-to-file

v1.3.0

Published

Nuxt module to merge and transform multiple API + GraphQL requests into a single one, like a payload extractor

Downloads

24

Readme

🎉 Nuxt APIs to file

Code Quality Dependencies Circle CI npm downloads npm version Donate

Nuxt module to merge and transform multiple API + GraphQL requests into a single one, 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

Configuration

N.B. : Shallow merge, not deep merge.


    // 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
                {
                    skip: false, // skip a request
                    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.items', // Check `dot-object` to know more
                    // 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: {},
                    // New, available with version >= 1.2
                    id: -1, // useful for debugging purpose, default = `the actual index in this array of requests + 1`
                    // For RECURSIVE api request with lists or nested data, N.B. : RECURSIVE, keep attention
                    pagination: {
                        pathBodyToPaginationParamValue: 'variables.nextToken', // [REQUIRED], witch params should update to match the next page? It depends on how you manage the pagination from the BE
                        pathResponseToTheNextPaginationValue: 'data.categories.listCategories.nextToken', // useful with Graphql, default = null
                        step: 1, // It always start with the `pathBodyToPaginationParamValue` param if specified, so this is used to increase this numeric value
                        maxIterations: 15, // Max iterations
                        lastPaginationValue: null // useful with Graphql, stop the next Iteration if 'pathResponseToTheNextPaginationValue' or 'pathBodyToPaginationParamValue' match this value
                    },
                },
            ],
        },

    };

    # 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 the-fastest-new-way of apis-to-json
            await dispatch(
                'build-data/getDataFromFile', // TTFB .. Guess 🤭
            );

        },
    };

    // 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

💼 Hire me

Contacts

💸 Are you feeling generous today?

If You want to share a beer, we can be really good friends

Paypal // Patreon // Ko-fi

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