@civic/storage-adapter
v0.1.0
Published
Civic Storage Adapter
Downloads
144
Maintainers
Keywords
Readme
Dynamic Storage Adapter
Overview
The Dynamic Storage Adapter provides an extensible and configurable mechanism for data storage. It combines the flexibility of different storage mechanisms with data validation using JSON schemas. This is especially useful for situations where parts of a data object should be stored in different locations or formats, such as sensitive data being encrypted before storage.
Features
- Multiple Storage Locations: Provides support for different storage mechanisms (e.g., in-memory, encrypted in-memory, etc.).
- Dynamic Configuration: Allows storage locations and mapping for different data properties to be set dynamically.
- Data Validation: Uses JSON schema for data validation before storage.
Basic Components
StorageLocation
An enum
that specifies the available storage mechanisms.
enum StorageLocation {
Local = "local",
Public = "public",
Private = "private"
}
StorageMapping
A mapping between object properties and where they should be stored.
type StorageMapping = Record<string, StorageLocation>;
User Schema
Example user schema to showcase how data can be defined and then stored using different storage mechanisms.
type User = {
firstName: string;
lastName: string;
age: number;
contact: {
phone: string;
email: string;
};
};
Storage Interface
An interface for the storage mechanisms. This allows easy extension and integration of new storage methods.
interface Storage<T> {
save(key: string, value: T): void;
get(key: string): T | null;
}
StorageAdapter
The core class responsible for the logic of where and how data should be stored, leveraging the provided configurations.
class StorageAdapter<T> {
...
}
Usage
Defining Storage Mechanisms
Storage mechanisms like InMemoryStorage
and MaskedMemoryStorage
are provided in the code. These classes implement the Storage
interface and define how data should be stored or retrieved.
Creating a Storage Adapter
To create a storage adapter for a specific data type (like User
), first define the schema, storage mapping, and storage location. Then, create an instance of the StorageAdapter
.
const storageLocation: Record<StorageLocation, Storage<Partial<User>>> = {
...
};
const storageMapping: StorageMapping = {
...
};
const userConfig: StorageConfig<User> = {
schema,
storageMapping,
storageLocation
};
const userAdapter = new StorageAdapter<User>(userConfig);
Storing and Retrieving Data
Use the save
and get
methods of the StorageAdapter
to store and retrieve data.
userAdapter.save({
...
});
console.log(userAdapter.get());
Example Payload to Backend
The code provides an example of a payload structure that can be sent to the backend. The backend can use the schema to validate incoming data and the storage mapping to determine how data should be stored.
{
"data": {
...
},
"storageMapping": {
...
}
}