github.com/benoitkugler/goacve@v0.0.0-20201217100549-151ce6e55dc8/server/frontend/bv/src/shared/logic/controller.ts (about) 1 import axios, { AxiosResponse } from "axios"; 2 import { Output } from "./notifications"; 3 import { PublicDocument } from "@/shared/logic/types"; 4 5 export const devMode = process.env.NODE_ENV != "production"; 6 export const UrlServerBase = devMode 7 ? "http://localhost:1323" 8 : window.location.origin; 9 10 export class BaseController { 11 notifications: Output; 12 13 constructor() { 14 this.notifications = new Output(); 15 } 16 17 uploadFile( 18 url: string, 19 file: File, 20 idDocCrypted: string 21 ): Promise<AxiosResponse<PublicDocument>> { 22 const form = new FormData(); 23 form.append("file", file, file.name); 24 form.append("crypted-id", idDocCrypted); 25 return axios.post(url, form); 26 } 27 28 // Renvoie `false` en cas d'erreur 29 async deleteDocument(doc: PublicDocument) { 30 try { 31 await axios.delete(UrlServerBase + "/document", { 32 params: { "id-crypted": doc.id_crypted } 33 }); 34 this.notifications.success = { 35 title: "Suppression", 36 message: "Le document a été supprimé avec succès." 37 }; 38 return true; 39 } catch (error) { 40 this.notifications.onAxiosError(error); 41 return false; 42 } 43 } 44 45 async uploadDocument(file: File, idDocCrypted: string) { 46 try { 47 const rep = await this.uploadFile( 48 UrlServerBase + "/document", 49 file, 50 idDocCrypted 51 ); 52 this.notifications.success = { 53 title: "Document modifié", 54 message: "Le document a bien été modifié." 55 }; 56 return rep.data; 57 } catch (error) { 58 this.notifications.onAxiosError(error); 59 } 60 } 61 } 62 63 /** remplace l'origin de l'url courante par celle 64 du serveur backend (n'affecte que le mode dev) 65 */ 66 export function adjustUrlOrigin() { 67 const loc = window.location; 68 const url = UrlServerBase + loc.pathname + loc.search + loc.hash; 69 return url.replace(/\/$/, ""); 70 } 71 72 export interface ControllerDocument { 73 deleteDocument(document: PublicDocument): Promise<boolean>; 74 uploadDocument( 75 file: File, 76 idCrypted: string 77 ): Promise<PublicDocument | undefined>; 78 } 79 80 /** Ajoute les meta données au fichier */ 81 export function fileMeta(file: File, meta: any) { 82 const formData = new FormData(); 83 formData.append("file", file, file.name); 84 formData.append("meta", JSON.stringify(meta)); 85 return formData; 86 }