Search code examples
angularngxs

ngxs selectively serialize properties in array


I have an AccountState which stores a list of accounts. The AccountState must be serialized to local storage so I use the Storage Plugin.

However I do not want to serialize each property of the accounts. For example I want to serialize the username but not the password.

Right now I import the Storage plugin like this:

NgxsStoragePluginModule.forRoot({
    key: [
        'account.accounts',
        'account.accounts.username' // <-- not working as accounts is an array not an object
    ]
})

So can I define that the array must be serialized with the username property but not with the password property?


Solution

  • I think there is no way to do that through configuration alone. You can, however, provide your own StorageEngine and modify the data there.

    import { NgxsStoragePluginModule, StorageEngine, STORAGE_ENGINE } from '@ngxs/storage-plugin';
    
    export class MyStorageEngine implements StorageEngine {
        get length(): number {
            // Your logic here
        }
    
        getItem(key: string): any {
            // Your logic here
        }
    
        setItem(key: string, val: any): void {
            // remove undesired values here
            let state = JSON.parse(val)
            state.accounts.accounts.forEach(acc => delete acc.password);
            localStorage.setItem(key, JSON.stringify(state));
        }
    
        removeItem(key: string): void {
            // Your logic here
        }
    
        clear(): void {
            // Your logic here
        }
    }
    
    @NgModule({
        imports: [
            NgxsModule.forRoot([]),
            NgxsStoragePluginModule.forRoot()
        ],
        providers: [
            {
            provide: STORAGE_ENGINE,
            useClass: MyStorageEngine
            }
        ]
    })
    export class MyModule {}
    

    Though, I wouldn't really reccomend this approach, since it will cost a lot of overhead because of the additional (de)serialization.

    Another way would be to introduce a self-written plugin which replaces the StoragePlugin and removes the undesired values before they are serialized.