api scaffold

This commit is contained in:
mProjectsCode 2022-05-04 19:09:54 +02:00
parent ddcc767573
commit 96d74a7732
6 changed files with 128 additions and 60 deletions

30
src/api/APIManager.ts Normal file
View file

@ -0,0 +1,30 @@
import {APIModel} from './APIModel';
import {APIRequestResult} from './APIRequestResult';
export class APIManager {
apis: APIModel[];
constructor() {
this.apis = [];
}
async query(query: string, types: string[] = []): Promise<APIRequestResult[]> {
console.log('MDB | api manager queried');
let res: APIRequestResult[] = [];
for (const api of this.apis) {
if (types.length === 0 || api.hasTypeOverlap(types)) {
const apiRes = await api.getByTitle(query);
// console.log(apiRes);
res = res.concat(apiRes);
}
}
return res;
}
registerAPI(api: APIModel): void {
this.apis.push(api);
}
}

33
src/api/APIModel.ts Normal file
View file

@ -0,0 +1,33 @@
import {APIRequestResult} from './APIRequestResult';
export abstract class APIModel {
name: string;
types: string[];
/**
* This function should query the api and return a list of matches. The matches should be caped at 20.
*
* @param title the title to query for
*/
abstract getByTitle(title: string): Promise<APIRequestResult[]>;
/**
* This function should return the metadata corresponding to the api result. An implementation should check first, if the result is from this api.
*
* @param item
*/
abstract getMataDataFromResult(item: APIRequestResult): string;
hasType(type: string): boolean {
return this.types.contains(type);
}
hasTypeOverlap(types: string[]): boolean {
for (const type of types) {
if (this.hasType(type)) {
return true;
}
}
return false;
}
}

View file

@ -1,6 +1,7 @@
export interface APIResult {
export interface APIRequestResult {
title: string,
type: string,
description?: string,
apiName: string,
data: any,
}

27
src/api/apis/TestAPI.ts Normal file
View file

@ -0,0 +1,27 @@
import {APIModel} from '../APIModel';
import {APIRequestResult} from '../APIRequestResult';
export class TestAPI extends APIModel {
constructor() {
super();
this.name = 'testAPI';
this.types = ['test'];
}
async getByTitle(title: string): Promise<APIRequestResult[]> {
console.log(`MDB | api "${this.name}" queried`);
return [
{title: 'test1', type: this.types[0], apiName: this.name, data: {length: 126}} as APIRequestResult,
{title: 'test2', type: this.types[0], apiName: this.name, description: 'some test description', data: {}} as APIRequestResult,
];
}
getMataDataFromResult(item: APIRequestResult): string {
if (item.apiName !== this.name) {
return '';
}
return '';
}
}