Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/timeraa/mongodb-caching
MongoDB with automatic Caching functionality using Keyv.
https://github.com/timeraa/mongodb-caching
automatic cache keyv mongodb
Last synced: 28 days ago
JSON representation
MongoDB with automatic Caching functionality using Keyv.
- Host: GitHub
- URL: https://github.com/timeraa/mongodb-caching
- Owner: Timeraa
- License: mpl-2.0
- Created: 2022-07-02T23:48:40.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-02-24T18:04:07.000Z (almost 2 years ago)
- Last Synced: 2024-12-04T20:50:38.316Z (29 days ago)
- Topics: automatic, cache, keyv, mongodb
- Language: TypeScript
- Homepage:
- Size: 26.4 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# MongoDB-Caching [![Version](https://img.shields.io/npm/v/mongodb-caching.svg)](https://www.npmjs.com/package/mongodb-caching)
MongoDB with automatic Caching functionality using Keyv.
## Installation
```bash
# npm
npm install mongodb-caching# yarn
yarn add mongodb-caching# pnpm
pnpm i mongodb-caching
```## Cached functions
_These functions automatically handle caching_
- find
- findOne
- countDocuments
- distinct**NOTE: When you update/insert/delete a document, the cache is not updated, you'll need to manually clear the cache using `customClass.clear()` or `customClass.keyv.clear()`**
## Usage
### Main
```ts
import { MongoClient } from "mongodb";import MongoDBCaching from "mongodb-caching";
interface UserCollectionSchema {
username: string;
}class User extends MongoDBCaching {
create(username: string) {
//* this.collection refers to MongoDB.Db.Collection
return this.collection.insertOne({ username });
}getUser(username: string) {
//* Internally handles caching
return this.findOne({ username });
}
}async function run() {
const mongodb = new MongoClient("mongoUri");const userCollection = new User(mongodb.db("main").collection("users"));
await userCollection.create("Timeraa");
console.log(await userCollection.getUser("Timeraa"));
}run();
```### With context
```ts
import { MongoClient } from "mongodb";import MongoDBCaching from "mongodb-caching";
interface UserCollectionSchema {
username: string;
ip: string;
}interface Context {
ip: string;
}class User extends MongoDBCaching {
create(username: string) {
//* this.collection refers to MongoDB.Db.Collection
return this.collection.insertOne({
username,
ip: this.context!.ip
});
}getUser(username: string) {
//* Internally handles caching
return this.findOne({ username });
}
}async function run() {
const mongodb = new MongoClient("mongoUri");const userCollection = new User(mongodb.db("main").collection("users"));
//* Context would be set in let's say a middleware
userCollection.setContext({ ip: "someIp" });await userCollection.create("Timeraa");
console.log((await userCollection.getUser("Timeraa"))?.ip);
}run();
```