New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@andrash/prisma-cache

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@andrash/prisma-cache

This is a tool that caches data from prisma. Note that this cache does not implement any cache invalidation mechanism, so it is only suitable for low data volume where **all data** should be cached.

npmnpm
Version
1.1.1
Version published
Weekly downloads
30
-16.67%
Maintainers
1
Weekly downloads
 
Created
Source

Welcome to Prisma Cache (by Andrash)

This package is a simple key-value store that stores data in both memory and any Prisma-compatible database.

本專案旨在提供一個簡單的「鍵->值」快取容器。它將資料存儲在記憶體中,並且同時將一個副本儲存在(任何與 Prisma 相容的) 資料庫中。這樣,當伺服器重新啟動時,即可從資料庫中將資料還原回到快取容器中。

Note that there is no built-in cache invalidation or free-up mechanism since the purpose of this tool is to create a simple key-value store that keeps all data (smaller scale) in memory and saves a copy in a database so it can be restored when the server is restarted.

請特別注意,這個工具並不提供快取失效或釋放機制。因為這個工具的主要用途在於建立一個簡單的「鍵->值」快取容器,並將較小規模的資料 全部 存儲在記憶體中,然後在伺服器重新啟動時,恢復這些資料。

It also uses the type definitions that come from the Prisma Client to ensure that the data stored in the cache is consistent with the Prisma model.

此外,它運用了來自 Prisma Client 的 TypeScript 型別定義,以確保儲存在快取中的資料與由 Prisma 模型所定義的一致。

Installation 安裝說明

npm i @andrash/prisma-cache

Please ensure that Prisma ORM is installed and Prisma client is generated.

使用前請先安裝 Prisma ORM 並且生成 Prisma client。

npm i @prisma/client
npx prisma generate

Usage 使用方法

import { PrismaCache } from "@andrash/prisma-cache";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
// Provide the user model and the primary key field name
const userCache = new PrismaCache(prisma, prisma.user, "user", "userId");

async function main() {
  // Connect to the database first.
  await prisma.$connect();

  // Be sure to initialize the cache before using it.
  // Do not init before connecting to the database, otherwise it will throw an error.
  userCache.init();

  // Load data from the database and store it in the cache, it will also return a copy of the data
  let dataList = await userCache.load();
  console.log(dataList); //[{userId: 1, name: 'Alice', age: 20}, {userId: 2, name: 'Bob', age: 30}]

  // Update data in both cache and database
  let data = await userCache.update(1, { name: "Alice Smith" });
  console.log(data); //{userId: 1, name: 'Alice Smith', age: 20}

  // Get data from cache without querying the database
  data = userCache.get(2);
  console.log(data); //{userId: 2, name: 'Bob', age: 30}

  // Patch data in cache **without updating the database**
  // This is a a dangerous operation since the cache and database will be out of sync
  // Only use this if are performing a more complex database operation directly with Prisma and you need the cache to reflect the changes.
  data = userCache.patch(2, { age: 31 });
  console.log(data); //{userId: 2, name: 'Bob', age: 31}

  // PrismaCache will mark the data as unsynced when you perform an unsafe operation that changes the data in the cache but not in the database.
  console.log(userCache.getIsSynced(2)); //false

  // And you can bring the data back to sync by calling the `save` method. This will update the database with the data in the cache.
  await userCache.save();

  // Or you can discard the changes in the cache and reload all the data from the database. This will also bring the data back to sync.
  await userCache.load();
}
main();

CRUD Operations 增/刪/改/查操作

There are two sets of CRUD (Create, Read, Update, Delete) operations: safe and unsafe.

Safe Operations:

  • All safe operations are async methods that will update the data in both the cache and the database:
    • async create() --> C
    • async load() --> R
    • async save() --> U
    • async update() --> U
    • async delete() --> D
    • async truncate() --> D
  • All data that has been changed by safe operations (except Read operations) will be marked as synced and will not be saved to the database when calling the save() method.

Unsafe Operations

  • All unsafe operations are synchronous methods that will only update the data in the cache:
    • set() --> C
    • get() --> R
    • getMany() --> R
    • patch() --> U
    • unset() --> D
    • clear() --> D
  • All data that has been changed by unsafe operations (except Read operations) will be marked as unsynced and will be saved to the database when calling the save() method.

Sync Status 同步狀態

You can also check the sync status of the data in the cache:

// Check if the data is synced with the database
console.log(userCache.getIsSynced(1)); //true

And even manage the sync status manually:

// Mark the data as unsynced
userCache.setIsUnsynced(1);
// Mark the data as synced
userCache.setIsSynced(1);

Use this feature with caution, as it can disrupt the built-in sync status tracking mechanism. Only use it when you know what you are doing.

Auto Save 自動儲存

This package also comes with an auto-save feature that will save all the unsynced data to the database in one batch after a certain delay.

// To enable the auto save feature, you can set the `autoSaveDelayMs` parameter in the constructor.
const autoSaveDelayMs = 5000; // 5 seconds
const userCache = new PrismaCache(
  prisma,
  prisma.user,
  "user",
  "userId",
  autoSaveDelayMs
);

// Or you can set it later
userCache.autoSaveDelayMs = 5000;

// You can also disable it by setting it to 0
userCache.autoSaveDelayMs = 0;

This feature will collect all the changes (unsynced data caused by unsafe operations) in a certain period of time (5 seconds for the example above) and save them to the database in one batch. This is useful when you have a lot of changes in a short period of time and you want to save them in one batch to reduce the number of database queries.

Iterating through the cache 遍歷所有快取資料

To iterate through all the data in the cache, you can do the following:

// With `userCache.forEach()` method
userCache.forEach((data, id, cache) => {
  console.log(data, id);
});

// With `userCache.ids` property
for (const id of userCache.ids) {
  const data = userCache.get(id);
  console.log(data, id);
}

FAQs

Package last updated on 16 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts