1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-11-25 23:09:22 +00:00

Can get API client information from database

This commit is contained in:
Pierre HUBERT 2019-11-22 09:31:13 +01:00
parent e7df7aab03
commit 2c4c914fbc
3 changed files with 116 additions and 0 deletions

12
src/entities/APIClient.ts Normal file
View File

@ -0,0 +1,12 @@
/**
* Information about an API client
*
* @author Pierre HUBERT
*/
export interface APIClient {
id: number,
name: string,
token: string,
domain: string,
}

View File

@ -1,3 +1,6 @@
import { APIClient } from "../entities/APIClient";
import { DatabaseHelper } from "./DatabaseHelper";
/** /**
* API Helper * API Helper
* *
@ -6,4 +9,36 @@
export class APIHelper { export class APIHelper {
private static SERVICES_TABLE = "comunic_api_services_tokens";
/**
* Get information about an API client
*
* @param name The name of the client to get
* @param token The token of the client to get
* @returns Information about the client or null
* if none found
*/
public static async GetClient(name: string, token: string) : Promise<APIClient | null> {
const entry = await DatabaseHelper.QueryRow({
table: this.SERVICES_TABLE,
where: {
service_name: name,
token: token
},
limit: 1
});
if(entry == null)
return null;
return {
id: entry.id,
name: entry.service_name,
token: entry.token,
domain: entry.client_domain
};
}
} }

View File

@ -7,6 +7,12 @@ import { conf } from "./ConfigHelper";
* @author Pierre HUBERT * @author Pierre HUBERT
*/ */
export interface QueryInformation {
table: string,
where ?: Object,
limit ?: number,
}
export class DatabaseHelper { export class DatabaseHelper {
private static connection : Connection; private static connection : Connection;
@ -38,4 +44,67 @@ export class DatabaseHelper {
}) })
} }
/**
* Query the database (SELECT)
*
* @param info Information about the query
*/
static async Query(info: QueryInformation) : Promise<Array<any>> {
// Prepare SQL request
let request = "SELECT * FROM " + info.table;
let args = [];
// Add where arguments
if(info.where) {
request += " WHERE ";
for(const k in info.where) {
if(!info.where.hasOwnProperty(k))
continue;
const v = info.where[k];
request += k;
request += v.startsWith("%") || v.endsWith("%") ? " LIKE " : " = "
request += "? AND "
args.push(v);
};
// Remove the last (useless) AND
request = request.substr(0, request.length - 4)
}
// Limit (if any)
if(info.limit)
request += " LIMIT " + info.limit;
// Execute request
return await new Promise((resolve, reject) => {
this.connection.query( request, args, (err, result, fields) => {
if(err) {
reject(err);
return;
}
resolve(result);
});
});
}
/**
* Query a single row on the database
*
* @param info Information about the request
* @returns First matching row / null if none found
*/
static async QueryRow(info : QueryInformation) : Promise<any | null> {
info.limit = 1;
const result = await this.Query(info);
if(result.length == 0)
return null;
return result[0];
}
} }