{"size": 1405, "ext": "js", "max_stars_repo_path": "typeform/aws/integration-lambda/typeform_client.js", "max_stars_repo_name": "code4me/4me-app-builder-nodejs", "max_stars_repo_stars_event_min_datetime": "2022-01-10T21:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T19:34:35.000Z", "max_issues_repo_path": "typeform/aws/integration-lambda/typeform_client.js", "max_issues_repo_name": "code4me/4me-app-builder-nodejs", "max_issues_repo_issues_event_min_datetime": "2021-04-24T17:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T17:04:45.000Z", "max_forks_repo_path": "typeform/aws/integration-lambda/typeform_client.js", "max_forks_repo_name": "code4me/4me-app-builder-nodejs", "max_forks_repo_forks_event_min_datetime": "2022-01-12T14:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T09:36:36.000Z"}
{"max_stars_count": 2, "max_issues_count": 1, "max_forks_count": 2, "avg_line_length": 25.5454545455, "max_line_length": 87, "alphanum_fraction": 0.5864768683}
'use strict';

const axios = require('axios');

class TypeformClient {
  constructor(token) {
    this.client = this.createClient('https://api.typeform.com', token);
  }

  createClient(url, bearerToken) {
    const headers = {};
    if (bearerToken) {
      headers['authorization'] = `Bearer ${bearerToken}`;
    }
    const axiosConfig = {
      baseURL: url,
      timeout: 30000,
      headers: headers,
    };

    return axios.create(axiosConfig);
  }

  async createWebhook(form, tag, secret, webhookUrl) {
    try {
      const response = await this.client.put(
        `/forms/${form}/webhooks/${tag}`,
        {
          url: webhookUrl,
          enabled: true,
          secret: secret,
          verify_ssl: true,
        });
      const responseBody = response.data;
      const errors = responseBody.description;
      if (errors) {
        console.error("Errors from TypeForm call:\n%j", responseBody);
        return {error: 'Unable to create webhook'};
      } else {
        return responseBody;
      }
    } catch (error) {
      if (error.response) {
        const response = error.response;
        const url = error.config.url;
        console.error(`Error from ${url}. ${response.status}: ${response.statusText}`);
      } else {
        console.error(error);
      }
      return {error: 'Error from Typeform create webhook call'};
    }
  }
}

module.exports = TypeformClient;