api.js (1827B)
1 import Notice from "./notice.js"; 2 3 /** 4 * Api. 5 */ 6 export default class Api { 7 8 /** 9 * Sending data to the server. 10 * 11 * @param formData formular data 12 * @returns a promise 13 */ 14 sendData = function( formData ) { 15 16 console.debug( "API form data", formData ); 17 18 let api = this; 19 return new Promise( (resolve, reject) => { 20 21 let load = fetch( './', { 22 'method':'POST', 23 headers: { 24 'Accept': 'application/json', 25 }, 26 body:formData 27 } ); 28 29 load.then( response => { 30 if ( ! response.ok ) 31 reject( "Failed to post" ); 32 33 return response.json(); 34 }).then( data => { 35 36 for( let value of data['notices'] ) { 37 38 let notice = new Notice(); 39 notice.setContext( value.type, value.id, value.name ); 40 notice.log = value.log; 41 notice.setStatus( value.status ); 42 notice.msg = value.text; 43 notice.show(); 44 45 if ( api.notifyBrowser ) 46 notice.notifyBrowser() 47 }; 48 49 if ( data.success ) { // Kein Fehler? 50 resolve(); 51 } 52 else { 53 // Validation errors 54 for( name of data['errors'] ) 55 this.validationErrorForField( name ); 56 57 reject('API request failed'); 58 } 59 60 } ).catch( cause => { 61 62 console.warn( { 63 message: 'API request failed', 64 cause : cause, 65 data : formData, 66 } ); 67 68 let msg = ''; 69 let description = ''; 70 try { 71 let parsedCause = JSON.parse( cause ); 72 msg = parsedCause.message; 73 description = parsedCause.cause.description; 74 } 75 catch( e ) { 76 msg = 'Internal CMS error'; 77 description = cause + "\n\n" + e; 78 } 79 80 let notice = new Notice(); 81 notice.setStatus('error'); 82 notice.msg = msg; 83 notice.log = description; 84 notice.show(); 85 86 reject( msg ); 87 } ); 88 } ); 89 90 } 91 92 93 validationErrorForField = function( nameOfField ) { 94 } 95 96 } 97