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

learning: unstorage #79

Open
Drew-Macgibbon opened this issue Jul 1, 2023 · 4 comments
Open

learning: unstorage #79

Drew-Macgibbon opened this issue Jul 1, 2023 · 4 comments
Assignees
Labels
🗣️ discuss further discussion is required

Comments

@Drew-Macgibbon
Copy link
Contributor

This will be a running thread of my findings about using unstorage with Nuxt/Nitro.

@Drew-Macgibbon Drew-Macgibbon self-assigned this Jul 1, 2023
@Drew-Macgibbon Drew-Macgibbon added the 🗣️ discuss further discussion is required label Jul 1, 2023
@Drew-Macgibbon
Copy link
Contributor Author

Drew-Macgibbon commented Jul 1, 2023

Configuring storage drivers inside nuxt.config.ts works like this:

export default defineNuxtConfig({
 nitro: {
    storage: {
      logs: {
        driver: 'vercelKV',
        base: 'incubrain:logs'
      }
    },
    devStorage: {
      logs: {
        driver: 'fs',
        base: './public/logs'
      }
    },
  },
})

devStorage is for the development environment, while storage is for any live environment (on Vercel)

logs is an arbitrary name, you can add as many of these as you want and configure your drivers accordingly accessing them by initiating useStorage like so const storage = useStorage('logs')

Then you can access the KV stores like so const storedData = await storage.getItem(fileName)

@Drew-Macgibbon
Copy link
Contributor Author

Built-in Drivers

unstorage has a range of built-in drivers, this list will likely grow. What I like is that we can easily swap out our drivers with a single line of code in the nuxt.config.ts which makes our architecture more scalable/dynamic.

Anything marked as N/A is something I can't see us using in the future

Drivers Link
azureStorageTable N/A
azureCosmos N/A
azureStorageBlob N/A
cloudflareKVHTTP N/A
cloudflare-kv-http N/A
cloudflare-kv-binding N/A
fs Maps data to the real filesystem using directory structure for nested keys. Supports watching using chokidar.
github Map files from a remote github repository (readonly).
http Use a remote HTTP/HTTPS endpoint as data storage. Supports built-in http server methods.
localStorage Store data in localStorage.
lruCache N/A
memory Keeps data in memory using Set
mongodb N/A
overlay N/A
planetscale This driver stores KV information in a Planetscale DB with columns of id, value, created_at and updated_at.
redis Store data in a Redis storage using ioredis.
azureKeyVault N/A
sessionStorage sessionStorage
vercelKV Store data in a Vercel KV Store.

@Drew-Macgibbon
Copy link
Contributor Author

Drew-Macgibbon commented Jul 1, 2023

Usage

  • Serverless architectures don't have access to fs inside serverless functions, only use in devStorage.
  • localStorage is client-only, unstorage doesn't implement anything like node-localstorage, this may change.
  • sessionStorage is client-only.
  • memory (Set) is theoretically available in any JS environment. (untested)

Set in JavaScript (memory):

It's a built-in object type for storing collections of unique values. It's great for quickly checking if a value is present in a collection, and for ensuring that there are no duplicates in the collection. However, Set only exists in memory and only lasts for the duration of the page session. If the page is refreshed or closed, the data in the Set is lost.

This is ideal for storing unique values or objects within a single session, so examples might include:

  • Unique user selections from a multi-select form or checkbox group.
  • Tracking unique IDs of items seen or interacted with during a session, like posts viewed on a social media feed.

localStorage:

It's a type of web storage that allows JavaScript websites and apps to store key-value pairs in a web browser with no expiration time. This means the data stored in localStorage persists even after the browser or tab is closed, or after a page refresh. However, it has a maximum storage limit (usually 5MB) and it's not a good choice for storing sensitive data, as the data is not automatically encrypted and can be accessed by any code running on the same domain.

This is best for storing data that should persist beyond the current session. Examples might include:

  • User preferences or settings that should apply across all sessions, like chosen language, theme color, or text size.
  • Data to improve user experience on return visits, such as previously viewed items on an ecommerce site, or a high score in a browser game.
  • Caching non-sensitive server data to reduce server calls, such as static page content or publicly available API data.

sessionStorage:

It's similar to localStorage but has a shorter lifespan. Data stored in sessionStorage gets cleared when the page session ends (i.e., when the browser or tab is closed). Like localStorage, it also has a storage limit and is not ideal for storing sensitive data.

This is useful for storing data that's only relevant to the current session, and should be cleared when the session ends. Examples could be:

  • Data for a multi-page form, where data entered on one page needs to be accessible on subsequent pages, but only within the same session.
  • Session-specific data like a server session ID or a non-persistent shopping cart that should be cleared when the user closes the browser.
  • Temporary data that is used to restore the state of a user interface, like an open dialog or active tab, if the page is refreshed.

@Drew-Macgibbon
Copy link
Contributor Author

Drew-Macgibbon commented Jul 1, 2023

Learnings:

You need to define return types of getItem(itemName) otherwise it defaults to StorageValue type.
StorageValue is of union type null | string | number | boolean | object.

What if we want an array?

 const storedArray = await storage.getItem<CustomType[]>(fileName) || []
 storedArray.push(newValue)
 const newArray  = [...storedArray, ...moreValues]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🗣️ discuss further discussion is required
Projects
None yet
Development

No branches or pull requests

1 participant