axios#Method TypeScript Examples

The following examples show how to use axios#Method. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: http.ts    From byteinspire-js-sdk with MIT License 6 votes vote down vote up
public upload(config: {
    headers: Headers;
    path?: string;
    fileName?: string;
    filePath?: string;
    url: string;
    data?: any;
    method?: Method;
  }) {
    return axios.request(config);
  }
Example #2
Source File: index.ts    From keptn-azure-devops-extension with Apache License 2.0 6 votes vote down vote up
/**
 * Send a generic triggered event based on the input parameters
 *
 * @param input Parameters
 * @param httpClient an instance of axios
 */
async function triggerGeneric(input: Params, httpClient: AxiosInstance) {
  let options: any = {
    method: <Method>"POST",
    url: input.keptnApiEndpoint + "/v1/event",
    headers: { "x-token": input.keptnApiToken },
    data: {
      type:
        "sh.keptn.event." +
        input.stage +
        "." +
        (input.deliveryParams != undefined
          ? input.deliveryParams.sequence
          : "delivery") +
        ".triggered",
      source: "azure-devops-plugin",
      specversion: "1.0",
    },
  };
  if (
    input.genericParams != undefined &&
    input.genericParams.body != undefined
  ) {
    options.data.data = JSON.parse(input.genericParams.body);
  }

  console.log("sending generic event ...");

  return httpClient(options)
    .catch(handleApiError)
    .then(response => storeKeptnContext(input, response))
}
Example #3
Source File: ContentDeliveryAPI.d.ts    From foundation-lib-spa-core with Apache License 2.0 6 votes vote down vote up
/**
     * Strongly typed variant of invokeControllerMethod
     *
     * @see   invokeControllerMethod()
     * @param content The content for which the controller must be loaded
     * @param method  The (case sensitive) method name to invoke on the controller
     * @param verb    The HTTP verb to use when invoking the controller
     * @param data    The data (if any) to send to the controller for the method
     */
    invokeTypedControllerMethod<TypeOut, TypeIn>(content: ContentLink, method: string, verb?: Method, data?: TypeIn): Promise<ActionResponse<TypeOut>>;
Example #4
Source File: pd.ts    From pagerduty-cli with MIT License 6 votes vote down vote up
public async fetchWithSpinner(endpoint: string, p: {
    params?: object;
    headers?: object;
    method?: Method;
    data?: object;
    activityDescription?: string;
    stopSpinnerWhenDone?: boolean;
    fetchLimit?: number;
  } = {
    method: 'get',
    activityDescription: 'Fetching',
    stopSpinnerWhenDone: true,
  }): Promise<any[]> {
    this.progressState.stopSpinnerWhenDone = !(p?.stopSpinnerWhenDone === false)
    this.progressState.format = p.activityDescription ? p.activityDescription : 'Fetching'
    return this.fetch(endpoint, {params: p.params, headers: p.headers, method: p.method, data: p.data, callback: this.spinnerCallback, fetchLimit: p.fetchLimit})
  }
Example #5
Source File: request.ts    From byteinspire-js-sdk with MIT License 6 votes vote down vote up
public upload(originConfig: {
    headers: Headers;
    path?: string;
    filePath?: string;
    url: string;
    data?: any;
    method?: Method;
    onProgressUpdate?: UploadProgressHandler;
  }) {
    const config = this.getRequestConfig(originConfig);
    return this.instance.upload(config, this.baseURL);
  }
Example #6
Source File: request.ts    From genshin-kit-node with Apache License 2.0 6 votes vote down vote up
/**
 * @param path The function will use `${apiEndpoint}/${path}` as the request url, unless `path` starts with `http`
 */
export async function request(
  this: any,
  method: Method,
  path: string,
  data?: any
) {
  let query, body
  if (method.toLowerCase() === 'get') {
    query = data
  } else {
    body = data
  }

  return (
    await axios({
      method,
      url: path.startsWith('http') ? path : `${this._getApiEndpoint()}${path}`,
      headers: this._getHttpHeaders({ query, body }),
      data: body,
      params: query,
      ...(this.serverType === 'os' ? { withCredentials: true } : {}),
    })
  ).data as any
}
Example #7
Source File: index.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Send HTTP and return data, optionally serialized with class-transformer (helpful for Date serialization)
   * @param method HTTP method
   * @param url URL to send req to
   * @param responseClass Class with class-transformer decorators to serialize response to
   * @param body body to send with req
   */
  private async req<T>(
    method: Method,
    url: string,
    responseClass?: ClassType<ItemIfArray<T>>,
    body?: any,
    params?: any
  ): Promise<T>;
Example #8
Source File: OnboardingClient.ts    From helium-js with Apache License 2.0 6 votes vote down vote up
async execute<T>(method:Method, path: string, params?: Object) {
    try {
      const response: AxiosResponse<Response<T>> = await this.axios({
        method,
        url: path,
        data: params,
      })
      return response.data
    } catch (err) {
      if (axios.isAxiosError(err)) {
        return err.response?.data as Response<T>
      }
      throw err
    }
  }
Example #9
Source File: requestWrapper.ts    From ftx-api with MIT License 6 votes vote down vote up
private async getRequestSignature(
    method: Method,
    endpoint: string,
    secret: string | undefined,
    serialisedParams: string= ''
  ): Promise<{ timestamp: number; sign: string; }> {
    const timestamp = Date.now() + (this.timeOffset || 0);
    if (!secret) {
      return {
        timestamp,
        sign: ''
      };
    }

    let signature_payload;
    if (serialisedParams==='?') {
      signature_payload = `${timestamp}${method}/api/${endpoint}`;
    } else {
      signature_payload = `${timestamp}${method}/api/${endpoint}${serialisedParams}`;
    }

    return {
      timestamp,
      sign: await signMessage(signature_payload, secret)
    };
  }
Example #10
Source File: restCalls.ts    From keycloak-lambda-authorizer with Apache License 2.0 6 votes vote down vote up
export async function fetchData(url:string, method:Method = 'GET', headers?:any) {
  const ret = await fetch({
    url,
    method,
    headers,
    transformResponse: (req) => req,
    withCredentials: true,
    timeout: 29000,
  });
  return ret.data;
}
Example #11
Source File: BinanceService.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private async makeRequest(
        uri: string,
        method: Method,
        requiredAuthentication: AuthenticationMethod,
        ...parameters: [string, any][]
    ): Promise<any> {
        const apiUrl: URL = new URL(uri)

        for (const parameter of parameters) {
            if (this.isNullOrUndefined(parameter[1])) {
                continue
            }
            apiUrl.searchParams.append(parameter[0], parameter[1].toString())
        }

        const headers: any = this.setupAuthentication(
            apiUrl,
            requiredAuthentication
        )

        try {
            return await axios.request({
                method: method,
                url: apiUrl.href,
                headers: headers,
            })
        } catch (error) {
            this.log.jinfo({
                event: "requestError",
                params: error,
            })
        }
    }
Example #12
Source File: tdapiinterface.ts    From tda-api-client with GNU General Public License v3.0 6 votes vote down vote up
async function apiWriteResource(config: TacRequestConfig, method: Method, skipAuth: boolean): Promise<IWriteResponse> {
    if (!config.queueSettings || config.queueSettings.enqueue) {
        return new Promise((res, rej) => queue.qPush({ id: crypto.randomBytes(16).toString("hex"), config, method, res, rej, deleted: false }));
    }
    const requestConfig = {
        method: method,
        url: config.path,
        headers: {
            "Content-Type": "application/json",
        },
        data: config.bodyJSON,
    };

    if (!config.apikey && !skipAuth) {
        const authResponse = await getAPIAuthentication(config);
        const token = authResponse.access_token;
        // @ts-ignore
        requestConfig.headers["Authorization"] = `Bearer ${token}`;
    }

    return await performAxiosRequest(requestConfig, false) as IWriteResponse;
}
Example #13
Source File: qbittorrent.ts    From IYUU-GUI with GNU Affero General Public License v3.0 6 votes vote down vote up
async request(method: Method, path: string,
                  params?: any, data?: any,
                  headers?: any): Promise<AxiosResponse> {
        // qbt 默认Session时长 3600s,这里取 600s
        // FIXME 是否每次操作都login一下好些?就像PTPP一样
        if (this.isLogin === null || Date.now() - 600 * 1e3 > this.lastCheckLoginAt) {
            await this.ping()
        }

        return await axios.request({
            method: method,
            url: urljoin(this.config.address, '/api/v2', path),
            params: params,
            data: data,
            headers: headers,
            timeout: this.config.timeout,
            withCredentials: true
        })
    }
Example #14
Source File: HTTPParser.ts    From xxexploiter with MIT License 5 votes vote down vote up
public static fromString(fileContent: string): RequestStruct | null {
    try {
      fileContent = fileContent.replace(/(\r\n|\n|\r)/gm, "\n");

      let firstNewLineIndex = fileContent.indexOf("\n");
      if (firstNewLineIndex === -1) firstNewLineIndex = fileContent.length;

      const startLine = fileContent.substring(0, firstNewLineIndex);
      const startLineArray = startLine.split(" ");
      const method: Method = startLineArray[0] as Method;
      const path = startLineArray[1];
      let emptyLine = fileContent.indexOf("\n\n");
      if (emptyLine === -1) emptyLine = fileContent.length;

      const headersArray = fileContent.substring(firstNewLineIndex + 1, emptyLine).split("\n");
      const headers: Record<string, string> = {};
      const body = fileContent.substring(emptyLine + 2);

      headersArray.forEach(h => {
        const delimiterIndex = h.indexOf(":");
        const name = h.substring(0, delimiterIndex);
        const value = h.substring(delimiterIndex + 2);
        headers[name] = value;
      });

      //if full url is not in the request lets assume an http to host header
      let url: string;
      if (path.startsWith("http"))
        url = path;
      else
        url = "http://" + (headers['host'] || headers['Host']) + path;

      //let axios calculate the length, since we may change it
      delete headers["content-length"];
      delete headers["Content-Length"];
      return { body: body, headers: headers, method: method, url: url };
    }
    catch (ex) {
      console.error("[HTTPParser] - Error parsing request file");
      console.error(ex);
      return null;
    }
  }
Example #15
Source File: index.ts    From keptn-azure-devops-extension with Apache License 2.0 5 votes vote down vote up
/**
 * Request the evaluation-done event based on the startEvaluationKeptnContext task variable.
 * Try a couple of times since it can take a few seconds for keptn to evaluate.
 *
 * @param input Parameters
 * @param httpClient an instance of axios
 */
async function waitForEvaluationDone(input: Params, httpClient: AxiosInstance) {
  let keptnContext = tl.getVariable(input.keptnContextVar);
  console.log("using keptnContext = " + keptnContext);
  let evaluationScore = -1;
  let evaluationResult = "empty";

  let options: any = {
    method: <Method>"GET",
    headers: { "x-token": input.keptnApiToken },
    url:
      input.keptnApiEndpoint +
      "/mongodb-datastore/event?type=sh.keptn.event.evaluation.finished&keptnContext=" +
      keptnContext,
  };

  let c = 0;
  let max = (input.timeout * 60) / 10;
  let out;
  console.log("waiting in steps of 10 seconds, max " + max + " loops.");
  do {
    await delay(10000); //wait 10 seconds
    var response = await httpClient(options);
    if (response.data.events != undefined && response.data.totalCount == 1) {
      out = response.data.events[0];
      evaluationScore = out.data.evaluation.score;
      evaluationResult = out.data.evaluation.result;
    } else {
      if (++c > max) {
        evaluationResult = "not-found";
      } else {
        console.log("wait another 10 seconds");
      }
    }
  } while (evaluationResult == "empty");

  handleEvaluationResult(
    evaluationResult,
    evaluationScore,
    keptnContext,
    input
  );

  console.log("************* Result from Keptn ****************");
  console.log(JSON.stringify(out, null, 2));

  return evaluationResult;
}
Example #16
Source File: EpiComponent.d.ts    From foundation-lib-spa-core with Apache License 2.0 5 votes vote down vote up
/**
     * Invoke a method on the underlying controller for this component
     *
     * @param method The (Case sensitive) name of the method to invoke on the controller for this component
     * @param verb The HTTP method to use when invoking, defaults to 'GET'
     * @param args The data to send (will be converted to JSON)
     */
    protected invoke(method: string, verb?: Method, args?: object): Promise<ActionResponse<any>>;
Example #17
Source File: datasource.ts    From querybook with Apache License 2.0 5 votes vote down vote up
function syncDatasource<T>(
    method: Method,
    urlOrOptions: UrlOrOptions,
    data?: Record<string, unknown>,
    notifyOnError?: boolean
): ICancelablePromise<{ data: T }> {
    const url =
        typeof urlOrOptions === 'string' ? urlOrOptions : urlOrOptions['url'];

    let cancel: Canceler;
    const defaultConfig: AxiosRequestConfig = {
        url,
        baseURL: '/ds',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
        },
        method,
        cancelToken: new axios.CancelToken((c) => (cancel = c)),
    };

    if (data) {
        if (method === 'GET') {
            defaultConfig.params = {
                params: data,
            };
        } else {
            defaultConfig.data = data;
        }
    }

    const combinedConfig =
        typeof urlOrOptions === 'string'
            ? defaultConfig
            : {
                  ...defaultConfig,
                  ...urlOrOptions,
              };

    const request: ICancelablePromise<any> = axios.request(combinedConfig).then(
        (resp) => {
            if (resp.status === 200) {
                return Promise.resolve(resp.data);
            } else {
                return handleRequestException(resp, notifyOnError);
            }
        },
        (rej) => handleRequestException(rej, notifyOnError)
    );

    request.cancel = cancel;

    return request;
}
Example #18
Source File: BaseRestClient.ts    From bybit-api with MIT License 5 votes vote down vote up
/**
   * @private Make a HTTP request to a specific endpoint. Private endpoints are automatically signed.
   */
  private async _call(
    method: Method,
    endpoint: string,
    params?: any,
    isPublicApi?: boolean
  ): Promise<any> {
    const options = {
      ...this.globalRequestOptions,
      url: [this.baseUrl, endpoint].join(endpoint.startsWith('/') ? '' : '/'),
      method: method,
      json: true,
    };

    for (const key in params) {
      if (typeof params[key] === 'undefined') {
        delete params[key];
      }
    }

    const signResult = await this.prepareSignParams(params, isPublicApi);

    if (method === 'GET' || this.isSpotClient()) {
      options.params = signResult.paramsWithSign;
      if (options.params?.agentSource) {
        options.data = {
          agentSource: agentSource,
        };
      }
    } else {
      options.data = signResult.paramsWithSign;
    }

    return axios(options)
      .then((response) => {
        if (response.status == 200) {
          return response.data;
        }

        throw response;
      })
      .catch((e) => this.parseException(e));
  }
Example #19
Source File: requestWrapper.ts    From ftx-api with MIT License 5 votes vote down vote up
/**
   * @private Make a HTTP request to a specific endpoint. Private endpoints are automatically signed.
   */
  async _call(method: Method, endpoint: string, params?: string | object): GenericAPIResponse {
    const options = {
      ...this.globalRequestOptions,
      method: method,
      json: true
    };

    options.url = endpoint.startsWith('https') ? endpoint : [this.baseUrl, endpoint].join('/');

    const isGetRequest = method === 'GET';
    const serialisedParams = serializeParamPayload(isGetRequest, params, this.options.strict_param_validation);

    // Add request sign
    if (this.key && this.secret) {
      if (this.timeOffset === null && !this.options.disable_time_sync) {
        await this.syncTime();
      }

      const { timestamp, sign } = await this.getRequestSignature(method, endpoint, this.secret, serialisedParams);
      options.headers[getHeader('ts', this.options.domain)] = String(timestamp);
      options.headers[getHeader('sign', this.options.domain)] = sign;
    }

    if (isGetRequest) {
      options.url += serialisedParams;
    } else {
      options.data = params;
    }

    return axios(options).then(response => {
      if (response.status == 200) {
        return response.data;
      }

      throw response;
    }).catch(e => this.parseException(e));
  }
Example #20
Source File: resourceClient.ts    From apple-music-node with MIT License 5 votes vote down vote up
private request(method: Method, apiPath: string, params?: any): AxiosPromise {
    return this.axiosInstance.request({
      method: method,
      url: apiPath,
      params: params
    });
  }
Example #21
Source File: ajax.ts    From admin-fe with MIT License 5 votes vote down vote up
// 统一的 ajax 方法
async function ajax(
    method: Method = 'get',
    url: string = '',
    dataOrParams: object = {},
    headers: object = {},
): Promise<any> {
    if (!url) throw new Error('ajax url 为空')

    // 拼接 axios 配置
    const conf: AxiosRequestConfig = {
        method,
        url,
        headers,
    }
    if (method === 'get') conf.params = dataOrParams
    else conf.data = dataOrParams

    // 登录校验的 token
    const token = getItem(TOKEN_KEY_LOCAL_STORAGE)
    if (token) {
        // header 拼接 token - jwt
        conf.headers.authorization = `Bearer ${token}`
    }

    // 发送请求
    const res = await axios(conf)
    if (res.status !== 200) {
        console.error(res)
        messageError('请求状态码错误') // 弹出错误
    }

    // 处理结果
    const { data: resData } = res
    if (resData.errno === 0) return resData.data || {}
    console.error('请求错误', resData.errno, resData.message)
    messageError(resData.message) // 弹出错误
    return null

    // throw new Error(resData.message) // 抛出错误,以便使用方能通过 catch 截获
}
Example #22
Source File: endpoints.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Send a generic api request
   * @param {string} accessToken  The token used to authenticate request
   * @param {string} hostname     The base uri to send the request
   * @param {string} endpoint     The endpoint to send the request
   * @param {Method} method       Usually 'GET' or 'POST'
   * @param {ResponseType} type   The type of return object (Usually 'json')
   * @param {string} contentType  The content type of the request
   * @param {boolean} timeout     Whether the request should timeout or not
   * @param {any} data            The body of the request or null if a 'GET'
   */
  async sendRequest(
    accessToken: string | undefined,
    hostname: string,
    endpoint: string,
    method: Method,
    type: ResponseType = 'json',
    contentType = '',
    timeout = true,
    data?: any,
  ): Promise<any> {
    const headers: any = {
      'User-Agent': NestEndpoints.USER_AGENT_STRING,
      Referer: this.NEST_API_HOSTNAME,
    };

    if (contentType) {
      headers['Content-Type'] = contentType;
    }

    if (accessToken) {
      headers.Authorization = `Basic ${accessToken}`;
    }

    const url = hostname + endpoint;
    const req: AxiosRequestConfig = {
      method,
      url,
      data,
      headers,
      responseType: type,
      timeout: timeout ? API_TIMEOUT_SECONDS * 1000 : undefined,
    };

    return (await axios(req)).data;
  }
Example #23
Source File: Request.ts    From valorant.js with MIT License 5 votes vote down vote up
public setMethod(method: Method): RequestBuilder {
        this._method = method;
        return this;
    }
Example #24
Source File: custom-pricer-api.ts    From tf2autobot with MIT License 5 votes vote down vote up
private apiRequest<R extends CustomPricesResponse>(
        httpMethod: string,
        path: string,
        params?: Record<string, any>,
        data?: Record<string, any>
    ): Promise<R> {
        const options: AxiosRequestConfig = {
            method: httpMethod as Method,
            url: `${this.url ? this.url : 'https://api.prices.tf'}${path}`,
            headers: {
                // This one is okay to keep I guess
                'User-Agent': 'TF2Autobot@' + process.env.BOT_VERSION
            },
            timeout: 30000
        };

        if (this.apiToken) {
            options.headers = { Authorization: `Token ${this.apiToken}` };
        }

        if (params) {
            options.params = params;
        }

        if (data) {
            options.data = data;
        }

        return new Promise((resolve, reject) => {
            void axios(options)
                .then(response => {
                    resolve(response.data);
                })
                .catch(err => {
                    if (err) {
                        reject(err);
                    }
                });
        });
    }
Example #25
Source File: avalanche.ts    From avalanchejs with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   * @ignore
   */
  protected _request = async (
    xhrmethod: Method,
    baseurl: string,
    getdata: object,
    postdata: string | object | ArrayBuffer | ArrayBufferView,
    headers: AxiosRequestHeaders = {},
    axiosConfig: AxiosRequestConfig = undefined
  ): Promise<RequestResponseData> => {
    let config: AxiosRequestConfig
    if (axiosConfig) {
      config = {
        ...axiosConfig,
        ...this.requestConfig
      }
    } else {
      config = {
        baseURL: this.url,
        responseType: "text",
        ...this.requestConfig
      }
    }
    config.url = baseurl
    config.method = xhrmethod
    config.headers = headers
    config.data = postdata
    config.params = getdata
    // use the fetch adapter if fetch is available e.g. non Node<17 env
    if (typeof fetch !== "undefined") {
      config.adapter = fetchAdapter
    }
    const resp: AxiosResponse<any> = await axios.request(config)
    // purging all that is axios
    const xhrdata: RequestResponseData = new RequestResponseData(
      resp.data,
      resp.headers,
      resp.status,
      resp.statusText,
      resp.request
    )
    return xhrdata
  }
Example #26
Source File: http.ts    From byteinspire-js-sdk with MIT License 5 votes vote down vote up
async upload(config: {
    headers: Headers;
    path?: string;
    fileName?: string;
    filePath?: string;
    url: string;
    data?: any;
    method: Method;
    onProgressUpdate?: UploadProgressObject
  }, baseURL: string): Promise<{ data: any; }> {
    if (!config.filePath) {
      config.headers['x-tt-base64-encoded'] = 'true';
      config.data = base64Arraybuffer.encode(config.data as ArrayBuffer);
      return new Promise((resolve, reject) => {
        adapter.request({
          ...(config),
          header: config.headers,
          success(res: Response) {
            resolve(res);
          },
          fail(e: any) {
            reject(e);
          }
        });
      });
    }
    return new Promise((resolve, reject) => {
      const upoloadTask = adapter.uploadFile({
        url: baseURL + '/--mgc_file',
        filePath: config.filePath,
        name: 'file',
        header: config.headers,
        success(res: Response) {
          resolve({ data: JSON.parse(res.data as string) });
        },
        fail(e: any) {
          reject(e);
        }
      });
      if (typeof config.onProgressUpdate === 'function') {
        upoloadTask.onProgressUpdate(config.onProgressUpdate);
      }
    });
  }
Example #27
Source File: user-manager.ts    From malagu with MIT License 5 votes vote down vote up
async logout(): Promise<void> {
        this.userInfoSubject.next(undefined);
        const method = (this.logoutMethod || HttpMethod.POST) as Method;
        await this.restOperations.request({ url: this.logoutUrl, method });
        window.location.href = await this.pathResolver.resolve(this.logoutSuccessUrl.replace(/{redirect}/g, encodeURI(window.location.href)));
    }
Example #28
Source File: ContentDeliveryAPI.ts    From foundation-lib-spa-core with Apache License 2.0 5 votes vote down vote up
public async invoke<TypeOut extends unknown = any, TypeIn extends unknown = any>(content: ContentReference, method: string, verb?: Method, data?: TypeIn, requestTransformer?: AxiosTransformer): Promise<ActionResponse<TypeOut | NetworkErrorData, IContent>>
    {
        if (!this._config.EnableExtensions) return Promise.reject('Extensions must be enabled to use the invoke method');

        // Base configuration
        const apiId = ContentLinkService.createApiId(content, !this.InEditMode, this.InEditMode);
        const url = new URL(this.MethodService + apiId + '/' + method, this.BaseURL);

        // Default JSON Transformer for request data
        const defaultTransformer : AxiosTransformer = (reqData, reqHeaders) => {
            if (reqData) {
                reqHeaders['Content-Type'] = 'application/json';
                return JSON.stringify(reqData);
            }
            return reqData;
        }

        // Axios request config
        const options : Partial<AxiosRequestConfig> = {
            method: verb,
            data,

            transformRequest: requestTransformer || defaultTransformer
        }

        const createActionErrorResponse = (error : NetworkErrorData) : ActionResponse<NetworkErrorData, NetworkErrorData> => {
            const actionResponse : ActionResponse<NetworkErrorData, NetworkErrorData> = {
                actionName: method,
                contentLink: error.contentLink,
                currentContent: error,
                responseType: ResponseType.ActionResult,
                data: error,
                language: this.Language,
                name: typeof(error.name) === "string" ? error.name : error.name.value,
                url: error.contentLink.url
            }
            return actionResponse;
        }

        // Run the actual request
        return this.doRequest<ActionResponse<TypeOut | NetworkErrorData, IContent>>(url, options)
                .then(r => isNetworkError(r) ? createActionErrorResponse(r) : r)
                .catch((e : Error) => {
                    const errorResponse = this.createNetworkErrorResponse(e);
                    return createActionErrorResponse(errorResponse);
                });
    }
Example #29
Source File: fordpass.ts    From homebridge-fordpass with GNU General Public License v3.0 5 votes vote down vote up
async issueCommand(command: Command): Promise<string> {
    if (!this.config.access_token) {
      return '';
    }
    let method: Method = 'GET';
    let endpoint = '';
    switch (command) {
      case Command.START: {
        method = 'PUT';
        endpoint = `api/vehicles/v2/${this.vin}/engine/start`;
        break;
      }
      case Command.STOP: {
        method = 'DELETE';
        endpoint = `api/vehicles/v2/${this.vin}/engine/start`;
        break;
      }
      case Command.LOCK: {
        method = 'PUT';
        endpoint = `api/vehicles/v2/${this.vin}/doors/lock`;
        break;
      }
      case Command.UNLOCK: {
        method = 'DELETE';
        endpoint = `api/vehicles/v2/${this.vin}/doors/lock`;
        break;
      }
      case Command.REFRESH: {
        method = 'PUT';
        endpoint = `api/vehicles/v2/${this.vin}/status`;
        break;
      }
      default: {
        this.log.error('invalid command');
        break;
      }
    }

    if (endpoint) {
      const url = fordAPIUrl + endpoint;
      const options: AxiosRequestConfig = {
        method: method,
        url: url,
        headers: defaultHeaders,
      };

      if (options.headers) {
        options.headers['Application-Id'] = '71A3AD0A-CF46-4CCF-B473-FC7FE5BC4592';
        options.headers['auth-token'] = this.config.access_token;
      }
      const result = await axios(options);
      if (result.status !== 200) {
        handleError('IssueCommand', result.status, this.log);
        return '';
      }
      return result.data.commandId;
    }
    return '';
  }