Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a TwilioAPI client based on the Twilio OpenAPI spec #27

Merged
merged 2 commits into from
Jul 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@oclif/test": "^1.2.4",
"@twilio/cli-test": "^0.0.1",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"eslint": "^4.19.1",
"eslint-config-oclif": "^1.5.1",
"eslint-plugin-mocha": "^5.3.0",
Expand Down
31 changes: 25 additions & 6 deletions src/base-commands/twilio-client-command.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ const chalk = require('chalk');
const { flags } = require('@oclif/command');
const BaseCommand = require('./base-command');
const CliRequestClient = require('../services/cli-http-client');
const { TwilioApiClient } = require('../services/twilio-api');
const { TwilioCliError } = require('../services/error');
const { HELP_ENVIRONMENT_VARIABLES, UNEXPECTED_ERROR } = require('../services/messaging/help-messages');

class TwilioClientCommand extends BaseCommand {
constructor(argv, config, secureStorage) {
super(argv, config, secureStorage);
this.httpClient = undefined;
this.twilioClient = undefined;
this.twilio = undefined;
this.twilioApi = undefined;

// Ensure the 'runCommand' function is defined in the child class.
if (!this.runCommand || typeof this.runCommand !== 'function') {
Expand Down Expand Up @@ -46,11 +48,6 @@ class TwilioClientCommand extends BaseCommand {
}

this.httpClient = new CliRequestClient(this.id, this.logger);
this.twilioClient = require('twilio')(this.currentProject.apiKey, this.currentProject.apiSecret, {
accountSid: this.currentProject.accountSid,
region: this.currentProject.region,
httpClient: this.httpClient
});

// Run the 'abstract' command executor.
return await this.runCommand();
Expand Down Expand Up @@ -113,6 +110,28 @@ class TwilioClientCommand extends BaseCommand {

return results;
}

get twilioClient() {
if (!this.twilio) {
this.twilio = this.buildClient(require('twilio'));
}
return this.twilio;
}

get twilioApiClient() {
if (!this.twilioApi) {
this.twilioApi = this.buildClient(TwilioApiClient);
}
return this.twilioApi;
}

buildClient(ClientClass) {
return new ClientClass(this.currentProject.apiKey, this.currentProject.apiSecret, {
accountSid: this.currentProject.accountSid,
region: this.currentProject.region,
httpClient: this.httpClient
});
}
}

TwilioClientCommand.flags = Object.assign(
Expand Down
102 changes: 102 additions & 0 deletions src/services/api-schema/json-converter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const { logger } = require('../messaging/logging');

const SCHEMA_TYPE_TO_CONVERT_FUNC_MAP = {
array: 'convertArray',
boolean: 'convertBoolean',
integer: 'convertInteger',
number: 'convertNumber',
object: 'convertObject',
string: 'convertString'
};

/**
* A JSON Schema conversion orchestrator. It accepts a JSON schema and value
* and converts any fields that require ... conversion.
*/
class JsonSchemaConverter {
constructor() {
this.logger = logger;
}

convertSchema(schema, value) {
if (schema) {
const convertFunc = SCHEMA_TYPE_TO_CONVERT_FUNC_MAP[schema.type];

if (convertFunc) {
value = this[convertFunc](schema, value);
} else {
this.logger.debug(`No conversion function for "${schema.type}" schema type`);
}
}

return value;
}

convertArray(schema, value) {
if (!value) {
if (!schema.nullable) {
this.logger.debug('Null array found when nullable not allowed by schema: ' + JSON.stringify(schema));
}

return value;
}

// Recurse into the value using the schema's items schema.
return value.map(item => this.convertSchema(schema.items, item));
}

convertObject(schema, value) {
const converted = {};

let properties = schema.properties;

// If the schema has no properties, it is a free-form object with arbitrary
// property/value pairs. We'll map the object's keys to null-schemas so
// they'll be processed as-is (i.e., no type so just use the value).
if (!properties) {
const nameList = Object
.keys(value)
.map(name => ({ [name]: null }));

properties = Object.assign({}, ...nameList);
}

// Convert each object property and store it in the converted object, if a
// value was provided.
Object.entries(properties).forEach(([name, propSchema]) => {
const { propName, propValue } = this.convertObjectProperty(propSchema, name, value[name]);

if (propValue !== undefined) {
converted[propName] = propValue;
}
});

return converted;
}

convertObjectProperty(propSchema, propName, propValue) {
if (propValue !== undefined) {
propValue = this.convertSchema(propSchema, propValue);
}

return { propName, propValue };
}

convertBoolean(schema, value) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these just place holders?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, in case anyone wants to extend this and do some conversions.

return value;
}

convertInteger(schema, value) {
return value;
}

convertNumber(schema, value) {
return value;
}

convertString(schema, value) {
return value;
}
}

module.exports = JsonSchemaConverter;
56 changes: 56 additions & 0 deletions src/services/api-schema/twilio-converter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const JsonSchemaConverter = require('./json-converter');
const { camelCase } = require('../naming-conventions');

const STRING_FORMAT_TO_CONVERT_FUNC_MAP = {
'date-time': 'convertDateTime',
'date-time-rfc-2822': 'convertDateTime',
uri: 'convertUri'
};

/**
* A Twilio extension of the JSON Schema converter. We do additional date-time
* conversion and also camelCase object property names (keys).
*/
class TwilioSchemaConverter extends JsonSchemaConverter {
convertObjectProperty(propSchema, propName, propValue) {
// Convert the property *and* camelCase the key to make it more JSON-ic.
if (propValue !== undefined) {
propValue = this.convertSchema(propSchema, propValue);
}

return { propName: camelCase(propName), propValue };
}

convertString(schema, value) {
if (schema.format) {
const validateFunc = STRING_FORMAT_TO_CONVERT_FUNC_MAP[schema.format];

if (validateFunc) {
value = this[validateFunc](schema, value);
} else {
this.logger.debug(`No conversion function for "${schema.format}" schema format`);
}
}

return value;
}

convertDateTime(schema, value) {
// The date constructor accepts both ISO 8601 and RFC 2822 date-time formats.
const dateValue = new Date(value);

if (isNaN(dateValue)) {
this.logger.debug(`Date-Time value "${value}" is not properly formatted for "${schema.format}" schema format`);
return value;
}

return dateValue;
}

convertUri(schema, value) {
// We don't currently do any URI conversion. This just keeps from logging non-helpful debug.
return value;
}
}

module.exports = TwilioSchemaConverter;
2 changes: 2 additions & 0 deletions src/services/cli-http-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ class CliRequestClient {
this.logger.debug('User-Agent: ' + options.headers['User-Agent']);
this.logger.debug('-- END Twilio API Request --');

this.lastRequest = options;

return this.http(options);
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/services/naming-conventions.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ const capitalize = input => {
return input.trim().replace(/^[a-z]/, g => g[0].toUpperCase()); // upper the first character
};

const pascalCase = input => capitalize(camelCase(input));

module.exports = {
kebabCase,
camelCase,
snakeCase,
capitalize
capitalize,
pascalCase
};
Loading