Last active
January 14, 2022 15:39
-
-
Save FreeFly19/0441d816079b9b8517eced0062d1841d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Template { | |
id: string; | |
name: string; | |
} | |
interface Document { | |
} | |
interface State { | |
templates: Template[]; | |
documents: Document[]; | |
} | |
interface Command { | |
commandType: string; | |
apply(state: State): State; | |
revert(state: State): State; | |
} | |
class AddTemplateCommand implements Command { | |
constructor(private id: string, | |
private name: string) { | |
} | |
commandType: string = 'AddTemplateCommand'; | |
apply(state: State): State { | |
const newState: State = JSON.parse(JSON.stringify(state)); | |
newState.templates.push({id: this.id, name: this.name}); | |
return newState; | |
} | |
revert(state: State): State { | |
const newState: State = JSON.parse(JSON.stringify(state)); | |
newState.templates = newState.templates.filter(t => t.id !== this.id); | |
return newState; | |
} | |
} | |
/////////////////////// state.ts | |
let state: State = { | |
templates: [], | |
documents: [] | |
}; | |
function applyCommand(command: Command) { | |
state = command.apply(state); | |
const commandSyncQueue = JSON.parse(localStorage.getItem('queue')) || []; | |
commandSyncQueue.push(command); | |
localStorage.setItem('queue', JSON.stringify(commandSyncQueue)); | |
} | |
function syncCommand() { | |
const commandSyncQueue = JSON.parse(localStorage.getItem('queue')) || []; | |
fetch('/commands', {method: 'POST', body: JSON.stringify(commandSyncQueue)}) | |
.then(res => { | |
res.json().then(commands => { | |
commands.forEach(cmd => state = cmd.apply(state)); | |
}); | |
localStorage.setItem('queue', '[]'); | |
setTimeout(syncCommand, 1000); | |
}, () => { | |
setTimeout(syncCommand, 1000); | |
}); | |
} | |
syncCommand(); | |
////////////////// xxxx.component.ts | |
applyCommand(new AddTemplateCommand(Math.random() + '', 'Template 1')); | |
applyCommand(new AddTemplateCommand(Math.random() + '', 'Template 3')); | |
////////////////// xxxx.component.html | |
// <li *ngFor="let t of state.templates">{{t.name}}</li> | |
// Lens pattern |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment