Within my application, there are multiple forms that generate JSON objects with varying structures, including nested objects and arrays at different levels. These forms also support file uploads, storing URLs for downloading, names, and other information within the object.
Currently, I convert files to base64 strings and upload them to the backend before making any requests that involve files.
My goal is to enhance this process by waiting for the file upload API call to complete before modifying the user's request body and proceeding with the main post request. However, it seems that these operations are not sequential as intended, as the file gets uploaded in the backend but the user's object remains unmodified. Additionally, the file upload query appears to be executed multiple times without cause.
export class FilesCheckerInterceptor implements HttpInterceptor {
constructor(private filesService: FilesService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const data = request.body;
if (data) {
const uploaded: File[] = [];
this.traverse(data, files => {
files.forEach(file => {
const base64 = file.data;
const result = this.filesService.toFile(base64, file.name);
uploaded.push(result);
});
});
console.log(request);
return this.filesService.uploadFile(uploaded).pipe(
mergeMap(response => {
this.traverse(data, files => {
for (let i = 0; i < response.length; i++) {
files[i] = response[i];
}
});
return next.handle(request.clone({ body: data }));
}),
);
}
else {
return next.handle(request);
}
}
traverse(obj: any, action: (value: InternalFile[]) => void) {
if (obj !== null && typeof obj === 'object') {
Object.entries(obj).forEach(([key, value]) => {
if (key === 'attachments' && Array.isArray(value)) {
// const files = value as InternalFile[];
action(value);
}
else {
this.traverse(value, action);
}
})
}
}
}