# misc/persistedstore (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/persistedstore/

지속 저장소.

## PersistedStore extends Object

지속 저장소.
- 하나의 키에 상태 객체를 JSON 으로 저장하고, 바뀔 때 구독자에게 알린다.
- 판 번호(version)가 다르거나 파싱에 실패하면 기본값으로 되돌아간다.
- 점수판 / 사용자 설정처럼 "localStorage + JSON + 리스너" 골격이 반복되던 것을 표준화했다.

예제: 설정을 저장하고 바뀔 때 알림 받기

```js
import { PersistedStore } from "./build/vanilla.js";

const store = new PersistedStore("example.settings", { volume: 1, language: "en" }, 1);
const subscription = store.subscribe((state) => {
	console.log("changed", state.volume);
});
store.set({ volume: 0.5 });
const state = store.get();
console.log(state.volume, state.language);
store.unsubscribe(subscription);
store.reset();
```

- `constructor(storageKey, defaultState = {}, version = 1)` (constructor, since 0.3.0): 생성.
  - `storageKey` string: 상태를 둘 저장소 키.
  - `defaultState` object: 기본 상태. (저장된 것이 없거나 판이 다르면 이것을 복사해 쓴다)
  - `version` number: 저장 꼴의 판 번호. (저장된 판과 다르면 기본 상태로 되돌아간다)
- `get()` (method, since 0.3.0): 상태 반환. (복사본이 아니므로 직접 고치지 말고 set() 을 쓴다)
  - returns object: 지금 상태.
- `set(partialState)` (method, since 0.3.0): 상태 일부 갱신. (얕은 병합 후 저장하고 구독자에게 알린다)
  - `partialState` object: 바꿀 키와 값만 담은 객체.
- `replace(nextState)` (method, since 0.3.0): 상태 전체 교체.
  - `nextState` object: 새 상태. (얕게 복사해 쓴다)
- `reset()` (method, since 0.3.0): 기본값으로 초기화.
- `subscribe(subscriber)` (method, since 0.3.0): 구독. (해지 함수를 반환)
  - `subscriber` Function: (state) => void
  - returns Function: 해지 함수. (부르면 구독을 푼다)
- `unsubscribe(subscription)` (method, since 0.4.0): 구독 해지. (subscribe 가 돌려준 것을 넘긴다, 돌려받은 해지 함수를 부르는 것과 같다)
  - `subscription` Function: subscribe 가 돌려준 해지 함수. (모르는 것이면 아무것도 하지 않는다)
- `notify()` (method, since 0.3.0): 구독자 알림.
- `readFromStorage()` (method, since 0.3.0): 저장소에서 읽기.
  - returns object: 저장된 상태를 기본 상태 위에 덮은 새 객체. (없거나, 판이 다르거나, 풀 수 없으면 기본 상태의 복사본)
- `writeToStorage()` (method, since 0.3.0): 저장소에 쓰기.
- `readStoredText()` (method, since 0.4.0): 저장된 글 읽기. (없거나 못 읽으면 빈 글)
  - returns string: 저장된 JSON 글. 없거나 못 읽으면 빈 글.
- `setStorageBackend(storageBackend)` (method, since 0.4.0): 이 저장소만 쓰는 곳 갈아 끼우기. (null 이면 LocalStorage, 플랫폼의 저장소처럼 getItem, setItem, removeItem 을 가진 객체)
  - 갈아 끼운 곳에서 상태를 다시 읽고 구독자에게 알린다. 저장된 것이 없으면 기본값이다.
  - `storageBackend` { getItem: Function, setItem: Function, removeItem: Function } | null: 이 저장소만 쓸 곳. (null 이나 undefined 면 LocalStorage)

  예제: 플랫폼 저장소처럼 따로 둔 곳에 쓰기

  ```js
  import { PersistedStore } from "./build/vanilla.js";
  
  const itemMap = new Map();
  const store = new PersistedStore("example.progress", { stage: 1 }, 1);
  store.setStorageBackend({
  	getItem: (key) => {
  		return itemMap.has(key) ? itemMap.get(key) : null;
  	},
  	setItem: (key, value) => {
  		itemMap.set(key, value);
  	},
  	removeItem: (key) => {
  		itemMap.delete(key);
  	}
  });
  store.set({ stage: 3 });
  console.log(itemMap.get("example.progress"));
  ```

- `getStorageBackend()` (method, since 0.4.0): 이 저장소만 쓰는 곳 반환. (없으면 null)
  - returns object | null: 이 저장소만 쓰는 곳. 없으면 null.
- `getStorageKey()` (method, since 0.3.0): 저장 키 반환.
  - returns string: 저장소 키.
