Validate Map object in v6 #91
-
Not sure how to validate new Map() object, in your Validation Guide you have demonstrate boolean, string, number, array but not map. let map = new Map(); this.localStorage.setItem('test', map).subscribe(() => { SO how could I create schema to validate map object while getItem()? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Thanks for your interest for this lib. The JSON schema standard can only describe JSON, ie. literal objects. So for instances of specific classes, like this.localStorage.getItem(key).subscribe((result) => {
if (result instanceof Map) {}
}); Beware that in some special cases (private mode for example), the lib will fallback to For now, a safer way to store a const index = 'map';
const someMap = new Map<string, number>([['test1', 1], ['test2', 2]]);
/* Writing */
this.localStorage.setItem(index, Array.from(someMap)).subscribe();
/* Reading */
this.localStorage.getItem(index).pipe(
map((data) => new Map(data)),
).subscribe((data) => {
data.get('test1');
}); Then, you could use a JSON Schema to validate: const schema: JSONSchema = {
type: 'array',
items: {
type: 'array',
items: [
{ type: 'string' },
{ type: 'number' },
],
},
};
this.localStorage.getItem<[string, number][]>(index, { schema }).pipe(
map((data) => new Map(data)),
).subscribe((data) => {
data.get('test1');
}); I'll add this in v8 documentation, and think if the lib can do something about these cases. Thanks for pointing this out. |
Beta Was this translation helpful? Give feedback.
-
Edited my answer as it was inexact. |
Beta Was this translation helpful? Give feedback.
-
Thanks it worked! |
Beta Was this translation helpful? Give feedback.
Thanks for your interest for this lib.
The JSON schema standard can only describe JSON, ie. literal objects. So for instances of specific classes, like
Map
, you'll need to do your own validation, for example:Beware that in some special cases (private mode for example), the lib will fallback to
localStorage
, where data will be serialized. But a JavaScriptMap
is not serializable to JSON. To be exact, seriazalization works (JSON.stringify()
), but when unserializing (JSON.parse()
), you won't get a realMap
.For now, a safer way to store a
Map
would be this: