You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
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 = {
|
|
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){
|
|
resolve( {status: 'ok', notes: state.notes} );
|
|
};
|
|
|
|
endpoints.post['/search'] = function(resolve, reject, body){
|
|
const notes = state.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;
|
|
const note = state.notes.find( n => n.id===note_id );
|
|
if(note){
|
|
note.text = text;
|
|
note.modified = Date.now();
|
|
}
|
|
else{
|
|
state.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; |