Store Memory
Store data persistently in the 0G decentralized storage network for AI agents and applications.
Method
memory . store ( entry : MemoryEntry ): Promise < MemoryResult >
Parameters
The memory entry to store
Unique identifier for the memory entry
The data to store (will be JSON serialized)
Additional metadata for the entry
Tags for categorizing and searching the entry
Time-to-live in seconds (optional expiration)
Response
Whether the storage operation succeeded
The key of the stored entry
The content hash on the 0G network
When the entry was stored
Size of the stored data in bytes
Examples
Basic Storage
With Metadata and Tags
Batch Storage
import { Memory } from 'nebula-sdk' ;
const memory = new Memory ({
storageKey: 'user-session-123' ,
apiKey: 'your-api-key'
});
// Store simple data
const result = await memory . store ({
key: 'user_preferences' ,
value: {
theme: 'dark' ,
language: 'en' ,
notifications: true
}
});
console . log ( 'Stored successfully:' , result . success );
console . log ( 'Content hash:' , result . hash );
Advanced Usage
Conditional Storage
// Only store if key doesn't exist
try {
const existing = await memory . retrieve ( 'user_profile' );
if ( ! existing ) {
await memory . store ({
key: 'user_profile' ,
value: { name: 'John' , age: 30 }
});
}
} catch ( error ) {
// Key doesn't exist, safe to store
await memory . store ({
key: 'user_profile' ,
value: { name: 'John' , age: 30 }
});
}
Versioned Storage
// Store with version control
const version = Date . now ();
const result = await memory . store ({
key: `document_v ${ version } ` ,
value: {
content: 'Updated document content' ,
version: version ,
previousVersion: 'document_v1234567890'
},
metadata: {
author: 'user123' ,
changeType: 'content_update'
},
tags: [ 'document' , 'versioned' ]
});
// Also update the "latest" pointer
await memory . store ({
key: 'document_latest' ,
value: { currentVersion: `document_v ${ version } ` }
});
Large Data Storage
// Store large objects efficiently
const largeDataset = {
// ... large data object
};
// Compress before storing (optional)
const compressed = JSON . stringify ( largeDataset );
const result = await memory . store ({
key: 'large_dataset_001' ,
value: largeDataset ,
metadata: {
originalSize: JSON . stringify ( largeDataset ). length ,
compressed: false ,
dataType: 'training_data'
},
tags: [ 'dataset' , 'large' , 'training' ]
});
if ( result . size > 1024 * 1024 ) { // 1MB
console . warn ( 'Large storage detected:' , result . size , 'bytes' );
}
Error Handling
try {
const result = await memory . store ({
key: 'test_data' ,
value: { message: 'Hello World' }
});
if ( ! result . success ) {
console . error ( 'Storage failed' );
}
} catch ( error ) {
switch ( error . code ) {
case 'STORAGE_QUOTA_EXCEEDED' :
console . error ( 'Storage quota exceeded' );
break ;
case 'INVALID_KEY' :
console . error ( 'Invalid key format' );
break ;
case 'NETWORK_ERROR' :
console . error ( 'Network connection failed' );
break ;
case 'SERIALIZATION_ERROR' :
console . error ( 'Data cannot be serialized' );
break ;
default :
console . error ( 'Unexpected error:' , error . message );
}
}
Storage Patterns
Cache Pattern
class MemoryCache {
constructor ( private memory : Memory ) {}
async set ( key : string , value : any , ttl : number = 3600 ) {
return await this . memory . store ({
key: `cache: ${ key } ` ,
value ,
ttl ,
tags: [ 'cache' ]
});
}
async get ( key : string ) {
try {
const result = await this . memory . retrieve ( `cache: ${ key } ` );
return result ?. value ;
} catch {
return null ;
}
}
}
const cache = new MemoryCache ( memory );
await cache . set ( 'api_response' , { data: 'cached' }, 1800 );
Event Sourcing
// Store events for replay
async function storeEvent ( eventType : string , eventData : any ) {
const eventId = `event_ ${ Date . now () } _ ${ Math . random () } ` ;
return await memory . store ({
key: eventId ,
value: {
type: eventType ,
data: eventData ,
timestamp: new Date ()
},
metadata: {
eventType ,
aggregateId: eventData . aggregateId
},
tags: [ 'event' , eventType ]
});
}
await storeEvent ( 'user_registered' , {
aggregateId: 'user123' ,
email: 'user@example.com'
});
Best Practices
Key Naming
// Use consistent key naming patterns
const keyPatterns = {
user : ( id : string ) => `user: ${ id } ` ,
session : ( id : string ) => `session: ${ id } ` ,
cache : ( key : string ) => `cache: ${ key } ` ,
config : ( name : string ) => `config: ${ name } ` ,
temp : ( id : string ) => `temp: ${ id } `
};
await memory . store ({
key: keyPatterns . user ( '123' ),
value: { name: 'John' }
});
Data Validation
function validateMemoryEntry ( entry : MemoryEntry ) : boolean {
if ( ! entry . key || typeof entry . key !== 'string' ) {
throw new Error ( 'Invalid key' );
}
if ( entry . key . length > 255 ) {
throw new Error ( 'Key too long' );
}
if ( entry . value === undefined ) {
throw new Error ( 'Value is required' );
}
return true ;
}
// Use before storing
validateMemoryEntry ( entry );
await memory . store ( entry );
Batch operations when storing multiple entries
Use appropriate TTL to prevent storage bloat
Compress large data before storing
Use tags efficiently for better search performance
Monitor storage usage to avoid quota issues