type-collector is a typescript package that management LocalStorage, Session Storage and Cookies for Typescript, Objects, Array and Primitives types.
npm i type-collector --save
yarn add type-collector
import {TypeCollector} from 'type-collector';
let storage = TypeCollector.Factory.Storage;
storage.add("token","ooo.ooo.ooo")
.add("IDE",12)
.add("is-auth",true);
interface User{
id: string,
name: string;
age: number;
isActive: boolean;
}
let users: Array<User> = new Array<User>();
users.push(
{
id: TypeCollector.uuid(),
name: "Michael M. Delagarza",
age: 34,
isActive: true
},
{
id: TypeCollector.uuid(),
name: "Anita Alvarenga",
age: 23,
isActive: false
});
storage.add("users",users);
storage.get("token").then(res => {
console.log(res) //ooo.ooo.ooo
})
storage.get("is-auth").then(res => {
console.log(res) //true
})
storage.get<Array<User>>("users").then(users => {
users.forEach(user => {
console.log(user)
})
});
/*
{id: "2795f29d-c3b6-404e-baba-6e5a50fab87f", name: "Michael M. Delagarza", age: 34, isActive: true}
{id: "559d98de-a217-4125-9659-09851c419e53", name: "Anita Alvarenga", age: 23, isActive: false}
*/
storage.remove("token")
.remove("users")
storage.removeAll();
Session Storage similar to Local Storage but expires when the browser closed
let session = TypeCollector.Factory.Session;
session.add("id", TypeCollector.uuid())
.add("secure", false)
.add("post",{
message: "some post goes here",
date: new Date()
})
session.get<Object>("post").then(post => {
console.log(post)
//{message: "some post goes here", date: "2019-06-11T13:28:11.892Z"}
}).catch(error => {
console.log(error)
})
session.remove("id")
.remove("posts")
session.removeAll();
Cookies similar to Local Storage besides expiration date parameter
let cookie = TypeCollector.Factory.Cookie;
//add expired date
let expired = new Date("2020-01-01")
cookie.add("uuid",TypeCollector.uuid(), expired)
.add("users",users) //users array
cookie.get("uuid").then(uuid => console.log(uuid))
//cb3b619e-0d13-4d5c-a77a-5e5104a0cbc7
cookie.get<Array<User>>("users").then(users => {
users.forEach(user => {
console.log("id",user.id)
})
});
//b4a1d009-d86d-447e-976d-e2727ade9c9f
//b4a1d009-d86d-447e-976d-e2727ade9c9f
session.remove("uuid")
.remove("users")
session.removeAll();