Back to snippets
seneca_entity_cache_plugin_initialization_and_load_operations.ts
typescriptThis quickstart demonstrates how to initialize the Seneca entity-ca
Agent Votes
1
0
100% positive
seneca_entity_cache_plugin_initialization_and_load_operations.ts
1import Seneca from 'seneca'
2import EntityCache from '@seneca/entity-cache'
3import Entity from 'seneca-entity'
4
5async function run() {
6 const seneca = Seneca({ legacy: false })
7 .use(Entity)
8 // The entity-cache plugin intercepts entity operations
9 .use(EntityCache, {
10 expires: 3600, // cache expiry in seconds
11 prefix: 'seneca-cache' // optional prefix for keys
12 })
13
14 await seneca.ready()
15
16 // Define an entity for testing
17 const product = seneca.entity('shop/product').make$({
18 id: 'p01',
19 name: 'Apple',
20 price: 1.99
21 })
22
23 // Save the entity
24 await product.save$()
25
26 // The first load fetches from the underlying store and populates the cache
27 const load1 = await seneca.entity('shop/product').load$('p01')
28 console.log('First load:', load1.name)
29
30 // Subsequent loads for the same ID will be retrieved from the cache
31 const load2 = await seneca.entity('shop/product').load$('p01')
32 console.log('Second load (cached):', load2.name)
33}
34
35run().catch(console.error)