Fully resource agnostic jsonschemas interpreter
This commit is contained in:
85
front/app/src/common/crud/jsonschemas.service.ts
Normal file
85
front/app/src/common/crud/jsonschemas.service.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import {CrudService} from "./crud.service";
|
||||
import {Observable} from "rxjs";
|
||||
import {Injectable} from "@angular/core";
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class JsonschemasService {
|
||||
private rawSchemas: any | null = null;
|
||||
|
||||
constructor(private crudService: CrudService) {}
|
||||
|
||||
getSchemas(): Observable<Schema> {
|
||||
return new Observable<Schema>((observer) => {
|
||||
if (this.rawSchemas === null) {
|
||||
this.crudService.getSchema().subscribe((jsonSchemas: any) => {
|
||||
this.rawSchemas = jsonSchemas;
|
||||
observer.next(this.rawSchemas)
|
||||
});
|
||||
} else {
|
||||
observer.next(this.rawSchemas)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
buildResource(resourceName: string) {
|
||||
let resource;
|
||||
|
||||
resource = { ... this.rawSchemas.components.schemas[resourceName]};
|
||||
resource.components = { schemas: {} };
|
||||
for (let prop_name in resource.properties) {
|
||||
let prop = resource.properties[prop_name];
|
||||
|
||||
if (this.is_reference(prop)) {
|
||||
let subresourceName = this.get_reference_name(prop);
|
||||
resource.components.schemas[subresourceName] = this.buildResource(subresourceName);
|
||||
}
|
||||
}
|
||||
|
||||
return resource;
|
||||
}
|
||||
|
||||
getCreateResource(resourceName: string): Observable<Schema> {
|
||||
return new Observable<Schema>((observer) => {
|
||||
this.getSchemas().subscribe(() => {
|
||||
observer.next(this.buildResource(resourceName + 'Create'))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
getUpdateResource(resourceName: string): Observable<Schema> {
|
||||
return new Observable<Schema>((observer) => {
|
||||
this.getSchemas().subscribe(() => {
|
||||
let resource = this.buildResource(resourceName + 'Read');
|
||||
let updateResource = this.rawSchemas.components.schemas[resourceName + 'Update']
|
||||
|
||||
for (let prop_name in resource.properties) {
|
||||
if (! updateResource.properties.hasOwnProperty(prop_name)) {
|
||||
if (this.is_reference(resource.properties[prop_name])) {
|
||||
let subresourceName = this.get_reference_name(resource.properties[prop_name]);
|
||||
resource.components.schemas[subresourceName].readOnly = true;
|
||||
} else {
|
||||
resource.properties[prop_name].readOnly = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observer.next(resource);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private is_reference(prop: any) {
|
||||
return prop.hasOwnProperty('$ref');
|
||||
}
|
||||
|
||||
private get_reference_name(prop: any) {
|
||||
return prop['$ref'].substring(prop['$ref'].lastIndexOf('/')+1);
|
||||
}
|
||||
}
|
||||
|
||||
export interface Schema {
|
||||
components: { };
|
||||
}
|
||||
Reference in New Issue
Block a user