Giter Club home page Giter Club logo

vue3-axios-idb-vuex-sync's Introduction

Contributors Forks Stargazers Issues MIT License


Logo

Vue3 Axios IDB Store Sync

Small projects that creates an Vuex store, populates it with backend data and stores the data in idb - then on next page refresh it only loads the delta!
Explore the docs »

View Demo · Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. Getting Started
  3. Roadmap
  4. Contributing
  5. License
  6. Contact

About The Project

This vuex store module aims to provide basic CRUD functionality for large datasets.

Features:

  • Stores data in idb at client side and synchronizes the idb on startup with the backend. Only changed entites will be loaded.
  • Indexes entites by ID
  • Provides Get, Delete, Save, Create functionality
  • We lowered initial page loading from 9 seconds to 200 ms

(back to top)

Getting Started

Installation

npm install vue3-axios-idb-vuex-sync -save

Installation Axios

Axios is needed for this project and needs to be correctly configured. Here is the recommended configuration:

install package

npm install axios -save

in main.js

axios.defaults.baseURL = import.meta.env.VITE_BACKEND_URL;

in .env.development (+ .env.production)

VITE_BACKEND_URL=http://localhost:8080/

(back to top)

Usage

endpointName: in these examples can be replaced to anything moduleName: for consistency normaly the same as endpoint name. This is the name of the Vuex store module

in store.js

import { createBackendIdbVuexDataSync } from 'vue3-axios-idb-vuex-sync';
...
export default createStore({
 modules: {
   'moduleName': createBackendIdbVuexDataSync(
       { endpoint: 'endpointName' },
     )
   },
});

in any component

   import { onMounted, computed } from 'vue';
   import { useStore } from 'vuex';
   ...
   const allEntites = computed(() => store.getters['moduleName/all']);
   ...
   onMounted(() => {
    store.dispatch('moduleName/initialize');
   });
   ...
   function deleteItem(id) {
     store.dispatch('moduleName/delete', { id })
   }

backend API needed

This plugin expects the following endpoints under your backend URL:

  1. POST /endpointName/ Creating an new entity Expects entity as JSON in body Returns saved entity as JSON
  2. GET /endpointName/ Get a list of ALL entities - as JSON list
  3. GET /endpointName/?lastCacheUpdate={timestampInMs} Get a list of all entities that have been changed since {timestampInMs} - as JSON list
  4. PUT /endpointName/{itemId} Saves an existing entity Expects entity as JSON in body Returns saved entity as JSON
  5. DELETE /endpointName/{itemId} Deletes an entity Expects no body and returns nothing

These are currently not configurable for consistency reasons. If you have a legacy API and need other endpoints feel free to make a pull request :)

frontend API

Options for backendDataSync

Attribute Description Default Optional
endpoint used to identify the backend URLs - false
dbVersion Version of the IDB - this should be increased on breaking entity changes 1 true
initDataItemCallback This callback will be called after initialization for every NEW entity.
This callback is used to transform entites and to do expensive precalculations.
For example: Date formating and status calculations
There is no need to make a deep copy of the entity. Just add / change new properties and return the entity.
Parameters:
1. ONE new entity the backend sends
- true
dataChangedCallback this callback will be called whenever an item was saved
Parameters:
1. store
2. saved entity the backend sends
- true
successCallback will be called whenever an action (loading, delete, create, update) was successfull. This is normaly used to show success messages.
Parameters:
1. task name (one of: loading, delete, create, update)
2. store
- true
startLoadingCallback This callback is used to show a loading overlay. It should return a method to hide the overlay. - true
namespaced If the module should be namespaced or not false true
indexes list of indexes that should be build up. Array of objects with attributes 'column' and 'unique'.
There is always an unique index with the idColumn build up. No need to add it here.
[] true
idColumn name of the column to identify entities 'id' true
autoRefresh turns the auto refresh on or off false true
autoRefreshInverallMs interval in ms whenever new entities should be automatically fetched 10000 true

Getters

Name Parameters Description
all - returns all entities
byId itemId returns an entity based on the value of the idColumn
byIndex {index, values}
index: index name
values: array of values to look up in the indexes
returns entities based on values in indexes. See Option 'indexes'
lastCacheUpdate - timestamp on the last time the cache was updated

Actions

moduleName/loadData

Needs to be called to initialize the module on application startup. All parameters are optional Parameters: showSuccess: default true. Determinates if the successCallback should be called. initData: Array of Entities that (can be) loaded from another source. This should normaly not be used. Used in case we bundle initialization requests to the backend into one init call. initCacheData: Same use case as above but contains data from idb

moduleName/update

Updates one entity by its id. Also removes it from IDB Parameters: Object with id property. Will be send like this to backend.

moduleName/add

Creates one entity. Also removes it from IDB Parameters: Object that will be send like this to backend.

moduleName/delete

Deletes one entity by its id. Also removes it from IDB Parameters: Object with id property

(back to top)

Roadmap

See the open issues for a full list of proposed features (and known issues).

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

License

Distributed under the MIT License. See LICENSE for more information.

(back to top)

Contact

kaiwerther - [email protected] / [email protected]

Project Link: https://github.com/kaiwerther/vue3-axios-idb-vuex-sync

(back to top)

vue3-axios-idb-vuex-sync's People

Contributors

kaiwerther avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.