Select Git revision
api.ts
Leah Tacke genannt Unterberg authored
api.ts 10.94 KiB
import {AxiosResponse, OpenAPIClientAxios, OpenAPIV3} from 'openapi-client-axios';
import {Client as MyBackendClient} from './api-schema/openapi';
import {handleError, inject, provide} from "vue";
import APISpec from './api-schema/openapi.json'
import type {Components, Paths} from './api-schema/openapi';
export type SourceDBType = Components.Schemas.SourceDBType;
export type KeepAliveResponse = Components.Schemas.KeepAliveResponse;
export type ColumnProperties = Components.Schemas.ColumnProperties;
export type SampleSummary = Components.Schemas.SampleSummary;
export type ForeignKeyParameters = Paths.MarkForeignKey.QueryParameters;
export type VirtualViewParameters = Paths.GetVirtualView.QueryParameters;
export type DBSchemaParameters = Paths.GetDbSchema.QueryParameters;
export type TableSchemaParameters = Paths.GetTableSchema.QueryParameters;
export type TableQueryParameters = Paths.QueryTable.QueryParameters;
export type TableProbeParameters = Paths.ProbeTable.QueryParameters;
export type DBProbeParameters = Paths.ProbeDb.QueryParameters;
export type DBQueryParameters = Paths.QueryDbSchema.QueryParameters;
export type ERDParameters = Paths.MakeErd.QueryParameters;
export type DBProbeBody = Paths.ProbeDb.RequestBody;
export type DBQueryBody = Paths.QueryDbSchema.RequestBody;
export type ERDBody = Paths.MakeFilteredErd.RequestBody;
export type VirtualViewCreationBody = Paths.CreateVirtualView.RequestBody;
export type ForeignKeyBody = Paths.MarkForeignKey.RequestBody;
export type MitM = Components.Schemas.MITM;
export type MitMDefinition = Components.Schemas.MITMDefinition;
export type MitMDataType = Components.Schemas.MITMDataType;
export type WrappedMitMDataType = Components.Schemas.WrappedMITMDataType;
export type MitMDataTypesDict = Paths.GetMitmDataTypes.Responses.$200;
export type VirtualViewCreation = Components.Schemas.VirtualViewCreationRequest;
export type CompiledVirtualView = Components.Schemas.CompiledVirtualView;
export type ConceptMapping = Components.Schemas.ConceptMappingInput;
export type MappingGroupValidationResult = Components.Schemas.MappingGroupValidationResult;
export type IndividualValidationResult = Components.Schemas.IndividualValidationResult;
export type ExportRequest = Components.Schemas.ExportRequest;
export type PublishedMitMResponse = Components.Schemas.PublishedMitMResponse;
export type TableMetaInfoResponse = Components.Schemas.TableMetaInfoBase;
export type DBMetaInfoResponse = Components.Schemas.DBMetaInfoBase;
export type TableProbeResponse = Components.Schemas.TableProbeBase;
export type DBProbeResponse = Components.Schemas.DBProbeBase;
export type VirtualViewResponse = Components.Schemas.VirtualViewResponse;
export type TableIdentifier = Components.Schemas.TableIdentifier
export namespace Mappings {
export type ConceptMapping = Components.Schemas.ConceptMappingInput
export type ConceptProperties = Components.Schemas.ConceptProperties
export type OwnedRelations = Components.Schemas.OwnedRelations
export type ForeignRelation = Components.Schemas.ForeignRelationInput
export type ForeignRelationInfo = Components.Schemas.ForeignRelationInfo
export type ForeignRelationDefs = {
[relationName: string] : ForeignRelationInfo
}
}
export namespace Transforms {
export type EditColumns = Components.Schemas.EditColumns
export type ReselectColumns = Components.Schemas.ReselectColumns
export type CastColumn = Components.Schemas.CastColumn
export type SimpleWhere = Components.Schemas.SimpleWhere
export type Limit = Components.Schemas.Limit
export type TableFilter = Components.Schemas.TableFilter
export type ExistingTable = Components.Schemas.ExistingTable
export type RawCompiled = Components.Schemas.RawCompiled
export type TypedRawQuery = Components.Schemas.TypedRawQuery
export type SimpleJoin = Components.Schemas.SimpleJoin
export type SimpleSQLOperator = Components.Schemas.SimpleSQLOperator
export type ExtractJson = Components.Schemas.ExtractJson
export type AddColumn = Components.Schemas.AddColumn
export type Base = ExistingTable | SimpleJoin | RawCompiled
export type Transform = EditColumns | ReselectColumns | TableFilter | Limit
export type ColumnCreations = AddColumn | ExtractJson
}
const backendUrl = (process.env.VITE_API_HOST ?? window.location.origin) + (process.env.VITE_API_PREFIX ?? '/api') // process.env.API_URL ?? 'http://localhost:8080' // import.meta.env?.VITE_API_URL ||
console.log(`Using following (backend) API_URL: ${backendUrl}`)
// const f = jsYaml.loadAll('./api-schema/openapi.yaml')
const openAPIClient = new OpenAPIClientAxios({
definition: APISpec as OpenAPIV3.Document,
withServer: {url: backendUrl, description: 'Backend Server'},
axiosConfigDefaults: {withCredentials: true}
})
const client = openAPIClient.initSync<MyBackendClient>()
function toParamList(params, type = 'query') {
if (!params) return null;
const paramList = []
for (const [k, v] of Object.entries(params)) {
paramList.push({
name: k, value: v, in: type
})
}
return paramList
}
function errorHandler(msg?) {
return err => {
console.log(msg ?? "Request failed:", err);
return null as undefined
}
}
export async function getClient(): Promise<MyBackendClient> {
return await openAPIClient.getClient<MyBackendClient>()
}
export async function keepAlive(){
return await client.keep_alive().catch(errorHandler('API is unreachable'))
}
async function startSession() {
return await client.start_session().catch(errorHandler())
}
async function stopSession() {
return await client.stop_session().catch(errorHandler())
}
async function uploadDB(sqliteFile) {
const formData = new FormData();
formData.append('sqlite', sqliteFile);
return await client.upload_db(null, formData as any).catch(errorHandler('Error uploading file'))
/*
const formData = new FormData();
formData.append('sqlite', sqliteFile);
return apiConnection.post('/setup/upload-db', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
*/
}
async function connectDB(url: string) {
return await client.connect_db(null, {db_url: url}).catch(errorHandler('Error connecting to DB'))
//return apiConnection.post('/setup/connect-db', {'db_url': url}).catch(err => console.error('Error connecting to DB:', err))
}
async function testDBConn() {
return await client.test_db_conn().catch(errorHandler())
}
//
async function getMitMs() {
return await client.get_mitms().catch(errorHandler())
}
async function getMitMDefinition(mitm: MitM) {
return await client.get_mitm_definition(toParamList({mitm})).catch(errorHandler())
}
async function getMitMDataTypes() {
return await client.get_mitm_data_types().catch(errorHandler())
}
//
async function reflectDB() {
return await client.reflect_db().catch(errorHandler('Error reflecting DB schema'))
}
async function getDBSchema(params?: DBSchemaParameters) {
return await client.get_db_schema(toParamList(params)).catch(errorHandler('Error retrieving DB schema'))
}
async function getTableSchema(params: TableSchemaParameters) {
return await client.get_table_schema(toParamList(params)).catch(errorHandler('Error retrieving DB schema'))
}
async function queryTable(params: TableQueryParameters) {
return await client.query_table(toParamList(params)).catch(errorHandler())
}
async function probeTable(params: TableProbeParameters) {
return await client.probe_table(toParamList(params)).catch(errorHandler())
}
async function probeDB(body: DBProbeBody, params?: DBProbeParameters) {
return await client.probe_db(toParamList(params), body).catch(errorHandler())
}
async function searchDB(body: DBQueryBody, params?: DBQueryParameters) {
return await client.query_db_schema(toParamList(params), body).catch(errorHandler())
}
async function makeERD(params: ERDParameters, body?: ERDBody) {
if (!body)
return await client.make_erd(toParamList(params)).catch(errorHandler())
else
return await client.make_filtered_erd(toParamList(params), body).catch(errorHandler())
}
//
async function markForeignKey(body: ForeignKeyBody, params?: ForeignKeyParameters) {
return await client.mark_foreign_key(toParamList(params), body).catch(errorHandler('Foreign key constraint could not be created'))
}
async function createVirtualView(body: VirtualViewCreation, params?: Paths.CreateVirtualView.QueryParameters) {
return await client.create_virtual_view(toParamList(params), body).catch(errorHandler('Error creating virtual view'))
}
async function createVirtualViewsBatch(body: VirtualViewCreation[], params?: Paths.CreateVirtualView.QueryParameters) {
return await client.create_virtual_views_batch(toParamList(params), body).catch(errorHandler('Error creating virtual views'))
}
async function dropVirtualView(params: Paths.DropVirtualView.QueryParameters) {
return await client.drop_virtual_view(toParamList(params)).catch(errorHandler('Error dropping virtual view'))
}
async function getCompiledView(params: Paths.GetCompiledVirtualView.QueryParameters) {
return await client.get_compiled_virtual_view(toParamList(params)).catch(errorHandler('Requested virtual view could not be compiled'))
}
async function getCompiledViews() {
return await client.get_compiled_virtual_views().catch(errorHandler('Virtual views could not be compiled'))
}
async function validateMappings(body: ConceptMapping[]) {
return await client.validate_concept_mappings(null, body).catch(errorHandler('Error validating MitM concept mappings'))
}
//
async function exportMitM(body: ExportRequest) {
return await client.export_mitm(null, body, {responseType: "blob"}).catch(errorHandler('Error exporting MitM mapped dataset'))
}
async function publishMitMExport(body: ExportRequest, use_streaming_export: boolean) {
return await client.publish_mitm_export(toParamList({use_streaming_export: use_streaming_export}), body).catch(errorHandler('Error publishing MitM mapped dataset export'))
}
async function deleteMitMExport(exportID: number) {
return await client.delete_mitm_export(toParamList({export_id: exportID} as Paths.DeleteMitmExport.QueryParameters)).catch(errorHandler('Error deleting MitM dataset export'))
}
async function deleteMitMExports() {
return await client.delete_mitm_exports().catch(errorHandler('Error deleting MitM dataset exports'))
}
export default {
async install(app, options) {
app.config.globalProperties.$apiClient = client
app.provide('apiClient', client)
//provide('apiClient', client)
//app.config.globalProperties.$apiConnection = apiConnection
}
}
export function useAPIClient() {
return client
}
export function useAPI() {
return {
startSession,
stopSession,
getDBSchema,
uploadDB,
connectDB,
getMitMs,
getMitMDefinition,
getMitMDataTypes,
reflectDB,
testDBConn,
queryTable,
probeTable,
probeDB,
searchDB,
makeERD,
getTableSchema,
markForeignKey,
createVirtualView,
createVirtualViewsBatch,
dropVirtualView,
validateMappings,
exportMitM,
publishMitMExport,
deleteMitMExport,
deleteMitMExports,
getCompiledView,
getCompiledViews
}
}