The base client to interact with Telefónica's 4th Platform and Cognitive Services.
npm install @telefonica/api-clientapi-client package includes a set of helper classes to facilitate the creation of API clients, typically to interact with Telefónica's 4th Platform and Cognitive Services.
ApiClient class which includes a common set of functionality (mainly for instantiation and authentication purposes) which any API client can extend and reuse.
fromStatusCode() from which errors can be instantiated from the statusCode returned by the remote service.
Bad Request - 400 response.
Forbidden - 403 response.
Not Found - 404 response.
Internal Server - 500 response.
Gateway Timeout - 504 response.
ApiError.fromStatusCode() method.
api.ts file automatically generated using the Swagger Codegen tool from the Swagger API specification file (typically located in the ./swagger directory) of the concrete remote service.
javascript
import * as _ from 'lodash';
import * as http from 'http';
const uuidv4 = require('uuid/v4');
const swagger: any = require('../swagger/fictional.json');
import { ApiClient, ApiError, ErrorCode, HttpMethod, Params } from '@telefonica/api-client';
import { FictionalServiceOperationResult, FictionalServiceApi } from './api';
/**
* Considering the fictionalServiceOperation() is a POST operation with id equal
* to "fictionalServiceOperationId" in the ./swagger/fictional.json file.
*/
const fictionalServiceOperationPath: string = _.findKey(swagger.paths, ['post.operationId', 'fictionalServiceOperationId']);
interface FictionalServiceOperationResponse {
response: http.IncomingMessage;
body: FictionalServiceOperationResult;
}
export class FictionalServiceClient extends ApiClient {
public readonly apiName: string = swagger.info.title;
constructor(basePath?: string, accessToken?: string) {
super(new FictionalServiceApi(basePath), accessToken);
}
private throwFictionalServiceError(method: HttpMethod, url: string, params: Params, reason: any) {
const statusCode: number = reason && reason.response && reason.response.statusCode;
throw ApiError.fromStatusCode(this.apiName, ErrorCode['$' + statusCode], method, url, params, reason);
}
public async fictionalServiceOperation(param1: boolean, param2: number, param3: string, correlator?: string): Promise {
const method: HttpMethod = HttpMethod.POST;
const url: string = super.basePath + fictionalServiceOperationPath;
const params: Params = { param1, param2, param3 };
try {
let response: FictionalServiceOperationResponse = await (this.api as any).fictionalServiceOperation(params, correlator || uuidv4());
/ Everything OK, response 2XX status code received. /
return response.body;
} catch (reason) {
/ Status code other than 2XX received or any other error thrown. /
this.throwFictionalServiceError(method, url, params, reason);
}
}
}
``