项目作者: LuXDAmore

项目描述 :
📞 Nuxt module to merge and transform multiple API + GraphQL requests into a single one, like a payload extractor
高级语言: JavaScript
项目地址: git://github.com/LuXDAmore/nuxt-apis-to-file.git
创建时间: 2019-12-06T11:10:50Z
项目社区:https://github.com/LuXDAmore/nuxt-apis-to-file

开源协议:MIT License

下载


🎉 Nuxt APIs to file

Code Quality
@luxdamore/nuxt-apis-to-file">Dependencies
Circle CI
@luxdamore/nuxt-apis-to-file"">npm downloads
@luxdamore/nuxt-apis-to-file"">npm version
Donate

Nuxt module to merge and transform multiple API + GraphQL requests into a single one, during build-time, 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.
  1. yarn add @luxdamore/nuxt-apis-to-file # or npm install --save @luxdamore/nuxt-apis-to-file

Configuration

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

  1. // nuxt.config.js
  2. export default {
  3. // Module installation
  4. modules: [ '@luxdamore/nuxt-apis-to-file' ], // nuxt < v2.9
  5. buildModules: [ '@luxdamore/nuxt-apis-to-file' ], // nuxt >= v2.9
  6. // Module config
  7. apisToFile: {
  8. file: {
  9. // The name of the file
  10. name: 'data',
  11. // The extension of the file
  12. ext: 'json',
  13. // The main folder where to save the generated file, you should add this path to your `.gitignore` file
  14. path: 'apis-to-file',
  15. // The `file.path` is always starting from the `srcDir`, but you can force it to the `static/` dir changing this
  16. startFromStaticDir: false,
  17. // Options passed directly to the `outputJson` method of the `fs-extra` library
  18. options: {},
  19. },
  20. // Hide console messages
  21. hideErrorsInConsole: false,
  22. hideGenericMessagesInConsole: false, // default = `! nuxtConfig.dev`
  23. // A sub-folder of `file.path` in which to place the file
  24. dir: null,
  25. // `@nuxtjs/axios` config is automatically injected, but you can override it here
  26. axios: {},
  27. // Your APIs to extract
  28. requests: [
  29. // Every request is passed to an `axios.create` instance
  30. {
  31. skip: false, // skip a request
  32. endpoint: 'https://awesome-api.com/give-me-my-blazing-fast-data', // default = `axios.url`
  33. method: 'get', // default = `axios.method || 'get'`
  34. // The params of the request, you can pass a graph-ql query too, check it in the example folder
  35. body: {},
  36. // Use this to map the response in a custom `key`
  37. field: 'categories', // default = `the actual index in this array of requests`
  38. // Usually, your data is always nested in one or more objects
  39. pathToData: 'data.categories.listCategories.items', // Check `dot-object` to know more
  40. // In case of no-response, what value do you prefer for your empty data?
  41. emptyValue: [],
  42. // Like headers, authentication or everything is required by this request
  43. config: {},
  44. // New, available with version >= 1.2
  45. id: -1, // useful for debugging purpose, default = `the actual index in this array of requests + 1`
  46. // For RECURSIVE api request with lists or nested data, N.B. : RECURSIVE, keep attention
  47. pagination: {
  48. pathBodyToPaginationParamValue: 'variables.nextToken', // [REQUIRED], witch params should update to match the next page? It depends on how you manage the pagination from the BE
  49. pathResponseToTheNextPaginationValue: 'data.categories.listCategories.nextToken', // useful with Graphql, default = null
  50. step: 1, // It always start with the `pathBodyToPaginationParamValue` param if specified, so this is used to increase this numeric value
  51. maxIterations: 15, // Max iterations
  52. lastPaginationValue: null // useful with Graphql, stop the next Iteration if 'pathResponseToTheNextPaginationValue' or 'pathBodyToPaginationParamValue' match this value
  53. },
  54. },
  55. ],
  56. },
  57. };
  1. # In this example the *response* is:
  2. `response: {
  3. data: {
  4. categories: {
  5. listCategories: [ DATA ],
  6. },
  7. },
  8. }`,
  9. # but the extracted file is only containing the chosen *pathToData* in the *field* key:
  10. `{ categories: [ DATA ] }`

Usage

  1. // store/index.js
  2. export const actions = {
  3. async nuxtServerInit(
  4. { dispatch },
  5. ) {
  6. // usual old-slowly-way
  7. await dispatch(
  8. 'items/getItemsCategories', // TTFB + ~200ms 😨
  9. );
  10. await dispatch(
  11. 'news/getNewsCategories', // TTFB + ~250ms 😱
  12. );
  13. // with the-fastest-new-way of apis-to-json
  14. await dispatch(
  15. 'build-data/getDataFromFile', // TTFB .. Guess 🤭
  16. );
  17. },
  18. };
  19. // Create a module to load the generated file
  20. // store/build-data.js
  21. const getFile = () => import(
  22. '~/apis-to-file/data.json'
  23. ).then(
  24. m => m.default || m
  25. );
  26. export const actions = {
  27. async getDataFromFile(
  28. { commit }
  29. ) {
  30. let itemsCategories = []
  31. , newsCategories = []
  32. ;
  33. try {
  34. const { categories, otherCategories } = await getFile();
  35. if( categories )
  36. itemsCategories = categories;
  37. if( otherCategories )
  38. newsCategories = otherCategories;
  39. } catch( e ) {
  40. console.error(
  41. {
  42. e,
  43. }
  44. );
  45. }
  46. commit(
  47. 'items/SET_ITEMS_CATEGORIES',
  48. itemsCategories,
  49. {
  50. root: true,
  51. }
  52. );
  53. commit(
  54. 'news/SET_NEWS_CATEGORIES',
  55. newsCategories,
  56. {
  57. root: true,
  58. }
  59. );
  60. }
  61. };

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.