import * as express from "express" ; import { ITodo , Todo , ITodoModel } from "../../models" ; export class RestTodo { constructor ( ) { } list ( request , response ) { Todo . find ( { } ) . exec ( ( error , todos ) => { return response . send ( { todos : todos || [ ] } ) ; } ) ; } create ( request , response ) { let todo = { created : new Date ( ) , title : request . body . title } ; Todo . create ( todo , ( error , todo ) => { if ( todo ) { return response . send ( todo ) ; } else { return response . status ( 400 ) . send ( { success : false , message : "Invalid parameters" } ) ; } } ) ; } find ( request , response ) { const id = request . params [ "todo" ] ; if ( id ) { Todo . findById ( id ) . exec ( ( error , todo ) => { if ( todo ) { return response . send ( todo ) ; } else { return response . status ( 404 ) . send ( { success : false , message : "Todo not found" } ) ; } } ) ; } else { response . status ( 400 ) . send ( { success : false , message : "Bad request" } ) ; } } update ( request , response ) { const id = request . params [ "todo" ] ; if ( id ) { Todo . findById ( id ) . exec ( ( error , todo ) => { if ( todo ) { todo . updated = new Date ( ) ; if ( request . body . title ) { todo . title = request . body . title ; } todo . save ( ) ; return response . send ( todo ) ; } else { return response . status ( 404 ) . send ( { success : false , message : "Todo not found" } ) ; } } ) ; } else { response . status ( 401 ) . send ( { success : false , message : "Unauthorized" } ) ; } } remove ( request , response ) { const id = request . params [ "todo" ] ; if ( id ) { Todo . findById ( id ) . exec ( ( error , todo ) => { if ( todo ) { todo . remove ( ) ; return response . send ( { success : true , message : "Todo removed sucessfully" } ) ; } else { return response . status ( 404 ) . send ( { success : false , message : "Todo not found" } ) ; } } ) ; } else { response . status ( 400 ) . send ( { success : false , message : "Bad request" } ) ; } } }