Skip to content

Instantly share code, notes, and snippets.

@up1
Last active January 10, 2025 04:45
Show Gist options
  • Save up1/f3f4bc56edf5f8c283320fabc4d5e827 to your computer and use it in GitHub Desktop.
Save up1/f3f4bc56edf5f8c283320fabc4d5e827 to your computer and use it in GitHub Desktop.
Keyv with javascript
// Redis
import KeyvRedis from '@keyv/redis';
const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));
// ใช้งานผ่าน namespace
const users = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'users' });
const cache = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'cache' });
// SQLite
import KeyvSqlite from '@keyv/sqlite';
const keyvSqlite = new KeyvSqlite('sqlite://path/to/database.sqlite');
const keyv = new Keyv({ store: keyvSqlite, ttl: 5000, namespace: 'cache' });
// การใช้งาน
await keyv.set('foo', 'expires in 1 second', 1000);
await keyv.set('foo', 'never expires');
await keyv.get('foo');
await keyv.delete('foo');
await keyv.clear();
// ทำการ monitor การใช้งานผ่าน Hook
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (key, value) => console.log(`Setting key ${key} to ${value}`));
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.POST_SET, (key, value) => console.log(`Set key ${key} to ${value}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment