Wondering what’s next for npm?Check out our public roadmap! »

    @telefonica/api-client
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.4 • Public • Published

    API Client

    The api-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.

    The most important class is the ApiClient class which includes a common set of functionality (mainly for instantiation and authentication purposes) which any API client can extend and reuse.

    On the other hand, a set of error classes are provided to be thrown in case the remote service responds with an error. These error classes are:

    • ApiError: The base API error class including a static method fromStatusCode() from which errors can be instantiated from the statusCode returned by the remote service.
    • BadRequestError: The error instantiated in case the remote service responds with a Bad Request - 400 response.
    • ForbiddenError: The error instantiated in case the remote service responds with a Forbidden - 403 response.
    • NotFoundError: The error instantiated in case the remote service responds with a Not Found - 404 response.
    • InternalServerError: The error instantiated in case the or service responds with a Internal Server - 500 response.
    • GatewayTimeoutError: The error instantiated in case the or service responds with a Gateway Timeout - 504 response.
    • UnknownStatusCodeError: The error instantiated in case an unknown status code is passed to the ApiError.fromStatusCode() method.

    Typically, an API client leans on the 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.

    Taking into all this, the code to build a new API client to interact with a fictional external service which exposes a "fictionalServiceOperation" operation as stated in its Swagger API specification file is as simple as:

    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<FictionalServiceOperationResult> {
            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);
            }
        }
    }

    Install

    npm i @telefonica/api-client

    DownloadsWeekly Downloads

    1

    Version

    1.0.4

    License

    UNLICENSED

    Unpacked Size

    89.6 kB

    Total Files

    32

    Last publish

    Collaborators

    • avatar
    • avatar
    • avatar
    • avatar