mirror of
https://github.com/tribufu/sdk-js
synced 2025-06-20 12:24:35 +00:00
Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
d4e9f48751 |
14
examples/client.js
Normal file
14
examples/client.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
// Copyright (c) Tribufu. All Rights Reserved.
|
||||||
|
// SPDX-License-Identifier: MIT AND Apache-2.0
|
||||||
|
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
import { TribufuClient } from "../build/index.mjs";
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const tribufu = TribufuClient.fromEnv();
|
||||||
|
console.log(await tribufu.getClientInfo());
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
@ -1,4 +1,3 @@
|
|||||||
#!/usr/bin/env sh
|
#!/usr/bin/env sh
|
||||||
|
|
||||||
nswag run ./src/api/api.nswag
|
nswag run ./src/api/api.nswag
|
||||||
nswag run ./src/translate/translate.nswag
|
|
||||||
|
@ -8,7 +8,7 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
|
|
||||||
import { TribufuApiBase } from "../core/base";
|
import { TribufuApiBase } from "./api.base";
|
||||||
|
|
||||||
export class TribufuApiGenerated extends TribufuApiBase {
|
export class TribufuApiGenerated extends TribufuApiBase {
|
||||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
1
src/api/api.include.ts
Normal file
1
src/api/api.include.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
import { TribufuApiBase } from "./api.base";
|
@ -4,7 +4,7 @@
|
|||||||
"documentGenerator": {
|
"documentGenerator": {
|
||||||
"fromDocument": {
|
"fromDocument": {
|
||||||
"json": "",
|
"json": "",
|
||||||
"url": "http://localhost:5000/openapi.json",
|
"url": "http://localhost:5000/v1/openapi.json",
|
||||||
"output": null,
|
"output": null,
|
||||||
"newLineBehavior": "Auto"
|
"newLineBehavior": "Auto"
|
||||||
}
|
}
|
||||||
@ -48,7 +48,7 @@
|
|||||||
"useLeafType": false,
|
"useLeafType": false,
|
||||||
"classTypes": [],
|
"classTypes": [],
|
||||||
"extendedClasses": [],
|
"extendedClasses": [],
|
||||||
"extensionCode": "../core/include.ts",
|
"extensionCode": "api.include.ts",
|
||||||
"generateDefaultValues": true,
|
"generateDefaultValues": true,
|
||||||
"excludedTypeNames": [],
|
"excludedTypeNames": [],
|
||||||
"excludedParameterNames": [],
|
"excludedParameterNames": [],
|
||||||
@ -67,7 +67,7 @@
|
|||||||
"templateDirectory": null,
|
"templateDirectory": null,
|
||||||
"serviceHost": null,
|
"serviceHost": null,
|
||||||
"serviceSchemes": null,
|
"serviceSchemes": null,
|
||||||
"output": "generated.ts",
|
"output": "api.generated.ts",
|
||||||
"newLineBehavior": "LF"
|
"newLineBehavior": "LF"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
133
src/api/client.ts
Normal file
133
src/api/client.ts
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
// Copyright (c) Tribufu. All Rights Reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import { TribufuApi } from ".";
|
||||||
|
import { GrantType, TokenHintType } from "./generated";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* **Tribufu Client**
|
||||||
|
*
|
||||||
|
* Use this class to interact with Tribufu OAuth service.
|
||||||
|
*/
|
||||||
|
export class TribufuClient extends TribufuApi {
|
||||||
|
private clientId: string | null = null;
|
||||||
|
private clientSecret: string | null = null;
|
||||||
|
|
||||||
|
private accessToken: string | null = null;
|
||||||
|
private refreshToken: string | null = null;
|
||||||
|
private expiresIn: number = 0;
|
||||||
|
|
||||||
|
constructor(clientId: string, clientSecret: string) {
|
||||||
|
if (!clientId || !clientSecret) {
|
||||||
|
throw new Error("ClientId and ClientSecret are required");
|
||||||
|
}
|
||||||
|
|
||||||
|
super({ credentials: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}` });
|
||||||
|
|
||||||
|
this.clientId = clientId;
|
||||||
|
this.clientSecret = clientSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Try to create a TribufuClient from environment variables.
|
||||||
|
*
|
||||||
|
* - This will only work if the environment variables are set.
|
||||||
|
*
|
||||||
|
* @param prefix A prefix for the environment variables. Default is `TRIBUFU`.
|
||||||
|
* @returns TribufuClient | null
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* // process.env.TRIBUFU_CLIENT_ID
|
||||||
|
* // process.env.TRIBUFU_CLIENT_SECRET
|
||||||
|
* const client = TribufuClient.fromEnv();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public static fromEnv(prefix?: string | null): TribufuApi | null {
|
||||||
|
if (typeof process === "undefined") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clientId = process.env[`${prefix || "TRIBUFU"}_CLIENT_ID`];
|
||||||
|
const clientSecret = process.env[`${prefix || "TRIBUFU"}_CLIENT_SECRET`];
|
||||||
|
if (clientId && clientSecret) {
|
||||||
|
return new TribufuClient(clientId, clientSecret);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private useClientCredentials(): void {
|
||||||
|
if (this.clientId && this.clientSecret) {
|
||||||
|
this.credentials = `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private useBearerCredentials(): void {
|
||||||
|
if (this.accessToken) {
|
||||||
|
this.credentials = `Bearer ${this.accessToken}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async login(username: string, password: string): Promise<boolean> {
|
||||||
|
this.useClientCredentials();
|
||||||
|
|
||||||
|
const response = await this.createToken({
|
||||||
|
grant_type: GrantType.Password,
|
||||||
|
code: null,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
refresh_token: null,
|
||||||
|
client_id: this.clientId,
|
||||||
|
redirect_uri: null,
|
||||||
|
code_verifier: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response) {
|
||||||
|
this.accessToken = response.access_token;
|
||||||
|
this.refreshToken = response.refresh_token;
|
||||||
|
this.expiresIn = response.expires_in;
|
||||||
|
this.useBearerCredentials();
|
||||||
|
}
|
||||||
|
|
||||||
|
return !!response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refresh(): Promise<boolean> {
|
||||||
|
this.useClientCredentials();
|
||||||
|
|
||||||
|
const response = await this.createToken({
|
||||||
|
grant_type: GrantType.Refresh_token,
|
||||||
|
code: null,
|
||||||
|
username: null,
|
||||||
|
password: null,
|
||||||
|
refresh_token: this.refreshToken,
|
||||||
|
client_id: this.clientId,
|
||||||
|
redirect_uri: null,
|
||||||
|
code_verifier: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response) {
|
||||||
|
this.accessToken = response.access_token;
|
||||||
|
this.refreshToken = response.refresh_token;
|
||||||
|
this.expiresIn = response.expires_in;
|
||||||
|
this.useBearerCredentials();
|
||||||
|
}
|
||||||
|
|
||||||
|
return !!response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public logout(): Promise<any> {
|
||||||
|
this.useClientCredentials();
|
||||||
|
|
||||||
|
const response = this.revokeToken({
|
||||||
|
token: this.refreshToken,
|
||||||
|
token_type_hint: TokenHintType.Refresh_token,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.accessToken = null;
|
||||||
|
this.refreshToken = null;
|
||||||
|
this.expiresIn = 0;
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
@ -2,8 +2,8 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
import { TRIBUFU_API_URL } from "..";
|
import { TRIBUFU_API_URL } from "..";
|
||||||
import { TribufuApiBase } from "../core/base";
|
import { TribufuApiBase } from "./api.base";
|
||||||
import { TribufuApiGenerated } from "./generated";
|
import { TribufuApiGenerated } from "./api.generated";
|
||||||
import { TribufuApiOptions } from "../options";
|
import { TribufuApiOptions } from "../options";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1 +0,0 @@
|
|||||||
import { TribufuApiBase } from "../core/base";
|
|
@ -1,84 +0,0 @@
|
|||||||
//----------------------
|
|
||||||
// <auto-generated>
|
|
||||||
// Generated using the NSwag toolchain v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org)
|
|
||||||
// </auto-generated>
|
|
||||||
//----------------------
|
|
||||||
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
// ReSharper disable InconsistentNaming
|
|
||||||
|
|
||||||
import { TribufuApiBase } from "../core/base";
|
|
||||||
|
|
||||||
export class TribufuTranslateGenerated extends TribufuApiBase {
|
|
||||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
|
||||||
private baseUrl: string;
|
|
||||||
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
|
||||||
|
|
||||||
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
|
||||||
super();
|
|
||||||
this.http = http ? http : window as any;
|
|
||||||
this.baseUrl = baseUrl ?? "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Translate a given text.
|
|
||||||
*/
|
|
||||||
translate(): Promise<void> {
|
|
||||||
let url_ = this.baseUrl + "/translate";
|
|
||||||
url_ = url_.replace(/[?&]$/, "");
|
|
||||||
|
|
||||||
let options_: RequestInit = {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return this.transformOptions(options_).then(transformedOptions_ => {
|
|
||||||
return this.http.fetch(url_, transformedOptions_);
|
|
||||||
}).then((_response: Response) => {
|
|
||||||
return this.processTranslate(_response);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected processTranslate(response: Response): Promise<void> {
|
|
||||||
const status = response.status;
|
|
||||||
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
|
||||||
{
|
|
||||||
return response.text().then((_responseText) => {
|
|
||||||
return;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TribufuTranslateError extends Error {
|
|
||||||
override message: string;
|
|
||||||
status: number;
|
|
||||||
response: string;
|
|
||||||
headers: { [key: string]: any; };
|
|
||||||
result: any;
|
|
||||||
|
|
||||||
constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
|
|
||||||
super();
|
|
||||||
|
|
||||||
this.message = message;
|
|
||||||
this.status = status;
|
|
||||||
this.response = response;
|
|
||||||
this.headers = headers;
|
|
||||||
this.result = result;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected isTribufuTranslateError = true;
|
|
||||||
|
|
||||||
static isTribufuTranslateError(obj: any): obj is TribufuTranslateError {
|
|
||||||
return obj.isTribufuTranslateError === true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any {
|
|
||||||
if (result !== null && result !== undefined)
|
|
||||||
throw result;
|
|
||||||
else
|
|
||||||
throw new TribufuTranslateError(message, status, response, headers, null);
|
|
||||||
}
|
|
@ -1,74 +0,0 @@
|
|||||||
{
|
|
||||||
"runtime": "Default",
|
|
||||||
"defaultVariables": null,
|
|
||||||
"documentGenerator": {
|
|
||||||
"fromDocument": {
|
|
||||||
"json": "",
|
|
||||||
"url": "http://localhost:5578/openapi.json",
|
|
||||||
"output": null,
|
|
||||||
"newLineBehavior": "Auto"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"codeGenerators": {
|
|
||||||
"openApiToTypeScriptClient": {
|
|
||||||
"className": "TribufuTranslateGenerated",
|
|
||||||
"moduleName": "",
|
|
||||||
"namespace": "",
|
|
||||||
"typeScriptVersion": 4.3,
|
|
||||||
"template": "Fetch",
|
|
||||||
"promiseType": "Promise",
|
|
||||||
"httpClass": "HttpClient",
|
|
||||||
"withCredentials": false,
|
|
||||||
"useSingletonProvider": false,
|
|
||||||
"injectionTokenType": "OpaqueToken",
|
|
||||||
"rxJsVersion": 6,
|
|
||||||
"dateTimeType": "String",
|
|
||||||
"nullValue": "Null",
|
|
||||||
"generateClientClasses": true,
|
|
||||||
"generateClientInterfaces": false,
|
|
||||||
"generateOptionalParameters": true,
|
|
||||||
"exportTypes": true,
|
|
||||||
"wrapDtoExceptions": false,
|
|
||||||
"exceptionClass": "TribufuTranslateError",
|
|
||||||
"clientBaseClass": "TribufuApiBase",
|
|
||||||
"wrapResponses": false,
|
|
||||||
"wrapResponseMethods": [],
|
|
||||||
"generateResponseClasses": true,
|
|
||||||
"responseClass": "SwaggerResponse",
|
|
||||||
"protectedMethods": [],
|
|
||||||
"configurationClass": null,
|
|
||||||
"useTransformOptionsMethod": true,
|
|
||||||
"useTransformResultMethod": false,
|
|
||||||
"generateDtoTypes": true,
|
|
||||||
"operationGenerationMode": "SingleClientFromOperationId",
|
|
||||||
"markOptionalProperties": false,
|
|
||||||
"generateCloneMethod": false,
|
|
||||||
"typeStyle": "Interface",
|
|
||||||
"enumStyle": "Enum",
|
|
||||||
"useLeafType": false,
|
|
||||||
"classTypes": [],
|
|
||||||
"extendedClasses": [],
|
|
||||||
"extensionCode": "../core/include.ts",
|
|
||||||
"generateDefaultValues": true,
|
|
||||||
"excludedTypeNames": [],
|
|
||||||
"excludedParameterNames": [],
|
|
||||||
"handleReferences": false,
|
|
||||||
"generateTypeCheckFunctions": false,
|
|
||||||
"generateConstructorInterface": true,
|
|
||||||
"convertConstructorInterfaceData": false,
|
|
||||||
"importRequiredTypes": true,
|
|
||||||
"useGetBaseUrlMethod": false,
|
|
||||||
"baseUrlTokenName": "API_BASE_URL",
|
|
||||||
"queryNullValue": "",
|
|
||||||
"useAbortSignal": false,
|
|
||||||
"inlineNamedDictionaries": false,
|
|
||||||
"inlineNamedAny": false,
|
|
||||||
"includeHttpContext": false,
|
|
||||||
"templateDirectory": null,
|
|
||||||
"serviceHost": null,
|
|
||||||
"serviceSchemes": null,
|
|
||||||
"output": "generated.ts",
|
|
||||||
"newLineBehavior": "LF"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
Reference in New Issue
Block a user