flat-cache 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,22 +1,19 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) Roy Riojas and Jared Wray
1
+ MIT License & © Jared Wray
4
2
 
5
3
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
4
+ of this software and associated documentation files (the "Software"), to
5
+ deal in the Software without restriction, including without limitation the
6
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7
+ sell copies of the Software, and to permit persons to whom the Software is
10
8
  furnished to do so, subject to the following conditions:
11
9
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
14
12
 
15
13
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
14
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
15
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
16
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
22
-
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,74 +1,191 @@
1
+ [<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
2
+
1
3
  # flat-cache
4
+ > A simple key/value storage using files to persist the data
5
+
6
+ [![codecov](https://codecov.io/gh/jaredwray/cacheable/graph/badge.svg?token=lWZ9OBQ7GM)](https://codecov.io/gh/jaredwray/cacheable)
7
+ [![tests](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml/badge.svg)](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
8
+ [![npm](https://img.shields.io/npm/dm/flat-cache.svg)](https://www.npmjs.com/package/flat-cache)
9
+ [![npm](https://img.shields.io/npm/v/flat-cache)](https://www.npmjs.com/package/flat-cache)
10
+ [![GitHub](https://img.shields.io/github/license/jaredwray/cacheable)](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
11
+
12
+ # Features
13
+ - A simple key/value storage using files to persist the data
14
+ - Uses a in-memory cache (via `CacheableMemory`) as the primary storage and then persists the data to disk
15
+ - Automatically saves the data to disk via `persistInterval` setting. Off By Default
16
+ - Easily Loads the data from disk and into memory with `load` or `loadFile`
17
+ - Uses `ttl` and `lruSize` to manage the cache and persist the data
18
+ - Only saves the data to disk if the data has changed even when using `persistInterval` or calling `save()`
19
+ - Uses `flatted` to parse and stringify the data by default but can be overridden using `parse` and `stringify` in options
20
+
21
+ # Table of Contents
22
+ - [Installation](#installation)
23
+ - [Getting Started](#getting-started)
24
+ - [Breaking Changes from v5 to v6](#breaking-changes-from-v5-to-v6)
25
+ - [Global Functions](#global-functions)
26
+ - [FlatCache Options (FlatCacheOptions)](#flatcache-options-flatcacheoptions)
27
+ - [API](#api)
28
+ - [Events (FlatCacheEvents)](#events-flatcacheevents)
29
+ - [Parse and Stringify for File Caching](#parse-and-stringify-for-file-caching)
30
+ - [How to Contribute](#how-to-contribute)
31
+ - [License and Copyright](#license-and-copyright)
32
+
33
+ # Installation
34
+ ```bash
35
+ npm install flat-cache
36
+ ```
37
+
38
+ # Getting Started
39
+ ```javascript
40
+ import { FlatCache } from 'flat-cache';
41
+ const cache = new FlatCache();
42
+ cache.setKey('key', 'value');
43
+ cache.save(); // Saves the data to disk
44
+ ```
2
45
 
3
- > A stupidly simple key/value storage using files to persist the data
46
+ lets add it with `ttl`, `lruSize`, and `persistInterval`
47
+ ```javascript
48
+ import { FlatCache } from 'flat-cache';
49
+ const cache = new FlatCache({
50
+ ttl: 60 * 60 * 1000 , // 1 hour
51
+ lruSize: 10000, // 10,000 items
52
+ expirationInterval: 5 * 1000 * 60, // 5 minutes
53
+ persistInterval: 5 * 1000 * 60, // 5 minutes
54
+ });
55
+ cache.setKey('key', 'value');
56
+ ```
4
57
 
5
- [![NPM Version](https://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache)
6
- [![tests](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml)
7
- [![codecov](https://codecov.io/github/jaredwray/flat-cache/branch/master/graph/badge.svg?token=KxR95XT3NF)](https://codecov.io/github/jaredwray/flat-cache)
8
- [![npm](https://img.shields.io/npm/dm/flat-cache)](https://npmjs.com/package/flat-cache)
58
+ This will save the data to disk every 5 minutes and will remove any data that has not been accessed in 1 hour or if the cache has more than 10,000 items. The `expirationInterval` will check every 5 minutes for expired items and evict them. This is replacement to the `save()` method with a `prune` option as it is no longer needed due to the fact that the in-memory cache handles pruning by `ttl` expiration or `lruSize` which will keep the most recent there.
9
59
 
10
- ## install
60
+ here is an example doing load from already existing persisted cache
11
61
 
12
- ```bash
13
- npm i --save flat-cache
62
+ ```javascript
63
+ import { load } from 'flat-cache';
64
+ const cache = load('cache1', './cacheAltDirectory');
14
65
  ```
15
66
 
16
- ## Usage
67
+ This will load the cache from the `./cacheAltDirectory` directory with the `cache1` id. If it doesnt exist it will not throw an error but will just return an empty cache.
68
+
69
+ # Breaking Changes from v5 to v6
17
70
 
18
- ```js
71
+ There have been many features added and changes made to the `FlatCache` class. Here are the main changes:
72
+ - `FlatCache` is now a class and not a function which you can create instances of or using legacy method `load`, `loadFile`, or `create`
73
+ - `FlatCache` now uses `CacheableMemory` as the primary storage and then persists the data to disk
74
+ - `FlatCache` now uses `ttl` and `lruSize` to manage the cache and persist the data
75
+ - `FlatCache` now uses `expirationInterval` to check for expired items in the cache. If it is not set it will do a lazy check on `get` or `getKey`
76
+ - `getKey` still exists but is now is an alias to `get` and will be removed in the future
77
+ - `setKey` still exists but is now is an alias to `set` and will be removed in the future
78
+ - `removeKey` still exists but is now is an alias to `delete` and will be removed in the future
79
+
80
+ Here is an example of the legacy method `load`:
81
+ ```javascript
19
82
  const flatCache = require('flat-cache');
20
83
  // loads the cache, if one does not exists for the given
21
84
  // Id a new one will be prepared to be created
22
85
  const cache = flatCache.load('cacheId');
86
+ ```
23
87
 
24
- // sets a key on the cache
25
- cache.setKey('key', { foo: 'var' });
26
-
27
- // get a key from the cache
28
- cache.getKey('key'); // { foo: 'var' }
88
+ Now you can use the `load` method and ES6 imports:
89
+ ```javascript
90
+ import { FlatCache } from 'flat-cache';
91
+ const cache = new FlatCache();
92
+ cache.load('cacheId');
93
+ ```
94
+ If you do not specify a `cacheId` it will default to what was set in `FlatCacheOptions` or the default property `cacheId` of `cache1` and default `cacheDir` of `./cache`.
29
95
 
30
- // fetch the entire persisted object
31
- cache.all(); // { 'key': { foo: 'var' } }
96
+ If you want to create a new cache and load from disk if it exists you can use the `create` method:
97
+ ```javascript
98
+ import { create } from 'flat-cache';
99
+ const cache = create({ cacheId: 'myCacheId', cacheDir: './mycache', ttl: 60 * 60 * 1000 });
100
+ ```
32
101
 
33
- // remove a key
34
- cache.removeKey('key'); // removes a key from the cache
102
+ # Global Functions
103
+
104
+ In version 6 we attempted to keep as much as the functionality as possible which includes these functions:
105
+
106
+ - `create(options?: FlatCacheOptions)` - Creates a new cache and will load the data from disk if it exists
107
+ - `createFromFile(filePath, options?: FlatCacheOptions)` - Creates a new cache from a file
108
+ - `clearByCacheId(cacheId: string, cacheDir?: string)` - Clears the cache by the cacheId
109
+ - `clearAll(cacheDirectory?: string)` - Clears all the caches
110
+
111
+
112
+ # FlatCache Options (FlatCacheOptions)
113
+ - `ttl?` - The time to live for the cache in milliseconds. Default is `0` which means no expiration
114
+ - `lruSize?` - The number of items to keep in the cache. Default is `0` which means no limit
115
+ - `useClone?` - If `true` it will clone the data before returning it. Default is `false`
116
+ - `expirationInterval?` - The interval to check for expired items in the cache. Default is `0` which means no expiration
117
+ - `persistInterval?` - The interval to save the data to disk. Default is `0` which means no persistence
118
+ - `cacheDir?` - The directory to save the cache files. Default is `./cache`
119
+ - `cacheId?` - The id of the cache. Default is `cache1`
120
+ - `parse?` - The function to parse the data. Default is `flatted.parse`
121
+ - `stringify?` - The function to stringify the data. Default is `flatted.stringify`
122
+
123
+ # API
124
+
125
+ - `cache` - The in-memory cache as a `CacheableMemory` instance
126
+ - `cacheDir` - The directory to save the cache files
127
+ - `cacheId` - The id of the cache
128
+ - `cacheFilePath` - The full path to the cache file
129
+ - `cacheDirPath` - The full path to the cache directory
130
+ - `persistInterval` - The interval to save the data to disk
131
+ - `changesSinceLastSave` - If there have been changes since the last save
132
+ - `load(cacheId: string, cacheDir?: string)` - Loads the data from disk
133
+ - `loadFile(pathToFile: string)` - Loads the data from disk
134
+ - `all()` - Gets all the data in the cache
135
+ - `items()` - Gets all the items in the cache
136
+ - `keys()` - Gets all the keys in the cache
137
+ - `setKey(key: string, value: any, ttl?: string | number)` - (legacy) Sets the key/value pair in the cache
138
+ - `set(key: string, value: any, ttl?: string | number)` - Sets the key/value pair in the cache
139
+ - `getKey<T>(key: string)` - Gets the value for the key or the default value
140
+ - `get<T>(key: string)` - Gets the value for the key or the default value
141
+ - `removeKey(key: string)` - Removes the key from the cache
142
+ - `delete(key: string)` - Removes the key from the cache
143
+ - `clear()` - Clears the cache
144
+ - `save(force? boolean)` - Saves the data to disk. If `force` is `true` it will save even if `changesSinceLastSave` is `false`
145
+ - `destroy()` - Destroys the cache and remove files
146
+
147
+ # Events (FlatCacheEvents)
148
+
149
+ Events have been added since v6 to allow for more control and visibility into the cache. Here are the events that are available:
150
+
151
+ - `on(event: 'save', listener: () => void)` - Emitted when the cache is saved
152
+ - `on(event: 'load', listener: () => void)` - Emitted when the cache is loaded
153
+ - `on(event: 'delete', listener: (key: string) => void)` - Emitted when the cache is changed
154
+ - `on(event: 'clear', listener: () => void)` - Emitted when the cache is cleared
155
+ - `on(event: 'destroy', listener: () => void)` - Emitted when the cache is destroyed
156
+ - `on(event: 'error', listener: (error: Error) => void)` - Emitted when there is an error
157
+
158
+ Here is an example of how to use the `error` events:
159
+
160
+ ```javascript
161
+ import { FlatCache, FlatCacheEvents } from 'flat-cache';
162
+ const cache = new FlatCache();
163
+ cache.on(FlatCacheEvents.error, (error) => {
164
+ console.error(error);
165
+ });
166
+ ```
35
167
 
36
- // save it to disk
37
- cache.save(); // very important, if you don't save no changes will be persisted.
38
- // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys
168
+ `FlatCacheEvents` is an enum that contains the event names for the `on` method. You do not have to use it but makes it easier to know what events are available.
39
169
 
40
- // loads the cache from a given directory, if one does
41
- // not exists for the given Id a new one will be prepared to be created
42
- const cache = flatCache.load('cacheId', path.resolve('./path/to/folder'));
170
+ # Parse and Stringify for File Caching
43
171
 
44
- // The following methods are useful to clear the cache
45
- // delete a given cache
46
- flatCache.clearCacheById('cacheId'); // removes the cacheId document if one exists.
172
+ By default `flat-cache` uses `flatted` to parse and stringify the data. This is to allow for more complex data structures to be saved to disk. If you want to override this you can pass in your own `parse` and `stringify` functions. Here is an example:
47
173
 
48
- // delete all cache
49
- flatCache.clearAll(); // remove the cache directory
174
+ ```javascript
175
+ import { FlatCache } from 'flat-cache';
176
+ const cache = new FlatCache({
177
+ parse: JSON.parse,
178
+ stringify: JSON.stringify,
179
+ });
50
180
  ```
51
181
 
52
- ## Motivation for this module
53
-
54
- I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make
55
- a script that will beutify files with `esformatter` only execute on the files that were changed since the last run.
56
- To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value`
57
- storage was needed and Bam! this module was born.
58
-
59
- ## Important notes
182
+ This will use `JSON.parse` and `JSON.stringify` to parse and stringify the data. This is useful if you want to use a different library or have a custom way of parsing and stringifying the data.
60
183
 
61
- - If no directory is especified when the `load` method is called, a folder named `.cache` will be created
62
- inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you
63
- might want to ignore the default `.cache` folder, or specify a custom directory.
64
- - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references
65
- - All the changes to the cache state are done to memory
66
- - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module
67
- intentionally dumb and simple
68
- - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call
69
- like: `cache.save( true /* noPrune */ )`.
184
+ **NOTE: This could cause issues if you are trying to load data that was saved with a different parser or stringifier.**
70
185
 
71
- ## License
186
+ # How to Contribute
72
187
 
73
- [MIT](LISCENCE) © [Jared Wray](https://jaredwray.com)
188
+ You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
74
189
 
190
+ # License and Copyright
191
+ [MIT © Jared Wray](./LICENSE)