import nanoid from './nanoid.min.js'; const api_stub = {}; // for mocking persistent state, for use by the fake endpoints, just as a real server endpoint would have DB access for state: const state = { bins: [ { id: nanoid(), notes: [ {id: nanoid(), text: 'Note one', modified: Date.now()}, {id: nanoid(), text: 'Note two', modified: Date.now()}, {id: nanoid(), text: 'Note three', modified: Date.now()} ] } ] }; const endpoints = { post: {} }; endpoints.post['/load-notes'] = function(resolve, reject, body){ let i = 0; if(body.bin_id){ i = state.bins.findIndex(b=>b.id===body.bin_id); // if there is no such bin, just return a well-formed response, but don't create such a bin server-side yet, until a save if(i === -1){ resolve( {status: 'ok', bin:{id:body.bin_id}, notes:[]} ); return; } } const bin = state.bins[i]; resolve( {status: 'ok', bin:{id:bin.id}, notes: bin.notes} ); }; endpoints.post['/search'] = function(resolve, reject, body){ const notes = state.bins.find(b=>b.id===body.bin_id).notes.filter(n => n.text.indexOf(body.search_term) !== -1 ) if(body.sorting==='new->old'){ notes.sort((a,b) => a.modified-b.modified); } else{ notes.sort((a,b) => b.modified-a.modified); } resolve( {status: 'ok', notes} ); }; endpoints.post['/save'] = function(resolve, reject, body){ const {note_id, text} = body; let bin = state.bins.find(b=>b.id===body.bin_id); if(!bin){ bin = {id: body.bin_id, notes: []}; state.bins.push(bin); } const note = bin.notes.find( n => n.id===note_id ); if(note){ note.text = text; note.modified = Date.now(); } else{ bin.notes.push({id: note_id, text, modified: Date.now()}); } resolve( {status: 'ok'} ); }; api_stub.post = function(url, body){ if(endpoints.post[url]){ return new Promise((resolve, reject)=>{ endpoints.post[url](resolve, reject, body); }); } else{ return new Promise((resolve, reject)=>{ reject( {error: 'no such endpoint'} ); }); } }; export default api_stub;