12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- class Auth {
- static _getKey() {
- return '__DEEP_RACER_TOKEN';
- }
- static _eventList = [];
- static get() {
- const res = localStorage.getItem(this._getKey());
- if (res) {
- try {
- return JSON.parse(res);
- } catch {
- return null;
- }
- }
- return null;
- }
- /**
- * 默认是追加数据,这样方便设置 schoolId
- */
- static set(auth, append = true) {
- let value = append ? this.get() : auth;
- if (append) {
- if (value) {
- value = {
- ...value,
- ...auth,
- };
- } else {
- value = auth;
- }
- }
- localStorage.setItem(this._getKey(), JSON.stringify(value));
- for (const callback of this._eventList) {
- callback(value);
- }
- }
- static remove() {
- localStorage.removeItem(this._getKey());
- for (const callback of this._eventList) {
- callback(null);
- }
- }
- static addListener(callback) {
- this._eventList.push(callback);
- window.addEventListener('storage', (e) => {
- if (e.key === this._getKey()) {
- callback(e.newValue ? JSON.parse(e.newValue) : null);
- }
- });
- }
- }
- window.Auth = Auth;
|