Skip to content

Commit

Permalink
refactor: Convert to native Promise and async/await (#8593)
Browse files Browse the repository at this point in the history
  • Loading branch information
juanjoDiaz committed Dec 16, 2020
1 parent 9bc1060 commit 84d423d
Show file tree
Hide file tree
Showing 14 changed files with 1,650 additions and 1,778 deletions.
2 changes: 1 addition & 1 deletion lib/classes/Variables.js
Expand Up @@ -841,7 +841,7 @@ class Variables {
if (type !== 'StringList' && param.startsWith('/aws/reference/secretsmanager')) {
try {
return JSON.parse(plainText);
} catch (err) {
} catch {
// return as plain text if value is not JSON
}
}
Expand Down
62 changes: 28 additions & 34 deletions lib/plugins/aws/configCredentials.js
@@ -1,6 +1,5 @@
'use strict';

const BbPromise = require('bluebird');
const os = require('os');
const credentials = require('./utils/credentials');

Expand Down Expand Up @@ -53,44 +52,39 @@ class AwsConfigCredentials {
};
}

configureCredentials() {
return BbPromise.try(() => {
// sanitize
this.options.provider = this.options.provider.toLowerCase();
this.options.profile = this.options.profile ? this.options.profile : 'default';
async configureCredentials() {
// sanitize
this.options.provider = this.options.provider.toLowerCase();
this.options.profile = this.options.profile ? this.options.profile : 'default';

// resolve if provider option is not 'aws'
if (this.options.provider !== 'aws') return null;
// resolve if provider option is not 'aws'
if (this.options.provider !== 'aws') return null;

// validate
if (!this.options.key || !this.options.secret) {
throw new this.serverless.classes.Error(
'Please include --key and --secret options for AWS.'
);
}

this.serverless.cli.log('Setting up AWS...');
// validate
if (!this.options.key || !this.options.secret) {
throw new this.serverless.classes.Error('Please include --key and --secret options for AWS.');
}

return credentials.resolveFileProfiles().then(profiles => {
if (profiles.has(this.options.profile)) {
// Only update the profile if the overwrite flag was set
if (!this.options.overwrite) {
const message = [
`Failed! ~/.aws/credentials already has a "${this.options.profile}" profile.`,
' Use the overwrite flag ("-o" or "--overwrite") to force the update',
].join('');
this.serverless.cli.log(message);
return null;
}
}
profiles.set(this.options.profile, {
accessKeyId: this.options.key,
secretAccessKey: this.options.secret,
});
this.serverless.cli.log('Setting up AWS...');

return credentials.saveFileProfiles(profiles);
});
const profiles = await credentials.resolveFileProfiles();
if (profiles.has(this.options.profile)) {
// Only update the profile if the overwrite flag was set
if (!this.options.overwrite) {
const message = [
`Failed! ~/.aws/credentials already has a "${this.options.profile}" profile.`,
' Use the overwrite flag ("-o" or "--overwrite") to force the update',
].join('');
this.serverless.cli.log(message);
return null;
}
}
profiles.set(this.options.profile, {
accessKeyId: this.options.key,
secretAccessKey: this.options.secret,
});

return credentials.saveFileProfiles(profiles);
}
}

Expand Down
128 changes: 58 additions & 70 deletions lib/plugins/aws/deployFunction.js
@@ -1,6 +1,5 @@
'use strict';

const BbPromise = require('bluebird');
const _ = require('lodash');
const crypto = require('crypto');
const path = require('path');
Expand All @@ -21,29 +20,25 @@ class AwsDeployFunction {
Object.assign(this, validate);

this.hooks = {
'deploy:function:initialize': () =>
BbPromise.bind(this)
.then(this.validate)
.then(this.checkIfFunctionExists),
'deploy:function:initialize': async () => {
await this.validate();
await this.checkIfFunctionExists();
},

'deploy:function:packageFunction': () =>
this.serverless.pluginManager.spawn('package:function'),

'deploy:function:deploy': () =>
BbPromise.bind(this)
.then(() => {
if (!this.options['update-config']) {
return this.deployFunction();
}

return BbPromise.resolve();
})
.then(this.updateFunctionConfiguration)
.then(() => this.serverless.pluginManager.spawn('aws:common:cleanupTempDir')),
'deploy:function:deploy': async () => {
if (!this.options['update-config']) {
await this.deployFunction();
}
await this.updateFunctionConfiguration();
await this.serverless.pluginManager.spawn('aws:common:cleanupTempDir');
},
};
}

checkIfFunctionExists() {
async checkIfFunctionExists() {
// check if the function exists in the service
this.options.functionObj = this.serverless.service.getFunction(this.options.function);

Expand All @@ -52,61 +47,55 @@ class AwsDeployFunction {
FunctionName: this.options.functionObj.name,
};

return this.provider
.request('Lambda', 'getFunction', params)
.then(result => {
this.serverless.service.provider.remoteFunctionData = result;
return result;
})
.catch(() => {
const errorMessage = [
`The function "${this.options.function}" you want to update is not yet deployed.`,
' Please run "serverless deploy" to deploy your service.',
' After that you can redeploy your services functions with the',
' "serverless deploy function" command.',
].join('');
throw new this.serverless.classes.Error(errorMessage);
});
try {
const result = await this.provider.request('Lambda', 'getFunction', params);

this.serverless.service.provider.remoteFunctionData = result;
return result;
} catch {
const errorMessage = [
`The function "${this.options.function}" you want to update is not yet deployed.`,
' Please run "serverless deploy" to deploy your service.',
' After that you can redeploy your services functions with the',
' "serverless deploy function" command.',
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
}

normalizeArnRole(role) {
async normalizeArnRole(role) {
if (typeof role === 'string') {
if (role.indexOf(':') === -1) {
const roleResource = this.serverless.service.resources.Resources[role];
if (role.indexOf(':') !== -1) {
return role;
}

if (roleResource.Type !== 'AWS::IAM::Role') {
throw new Error('Provided resource is not IAM Role.');
}
const roleProperties = roleResource.Properties;
if (!roleProperties.RoleName) {
throw new this.serverless.classes.Error('Role resource missing RoleName property');
}
const compiledFullRoleName = `${roleProperties.Path || '/'}${roleProperties.RoleName}`;
const roleResource = this.serverless.service.resources.Resources[role];

return this.provider
.getAccountInfo()
.then(
result => `arn:${result.partition}:iam::${result.accountId}:role${compiledFullRoleName}`
);
if (roleResource.Type !== 'AWS::IAM::Role') {
throw new Error('Provided resource is not IAM Role.');
}
const roleProperties = roleResource.Properties;
if (!roleProperties.RoleName) {
throw new this.serverless.classes.Error('Role resource missing RoleName property');
}
const compiledFullRoleName = `${roleProperties.Path || '/'}${roleProperties.RoleName}`;

return BbPromise.resolve(role);
const result = await this.provider.getAccountInfo();
return `arn:${result.partition}:iam::${result.accountId}:role${compiledFullRoleName}`;
}

return this.provider
.request('IAM', 'getRole', {
RoleName: role['Fn::GetAtt'][0],
})
.then(data => data.Arn);
const data = await this.provider.request('IAM', 'getRole', {
RoleName: role['Fn::GetAtt'][0],
});
return data.Arn;
}

callUpdateFunctionConfiguration(params) {
return this.provider.request('Lambda', 'updateFunctionConfiguration', params).then(() => {
this.serverless.cli.log(`Successfully updated function: ${this.options.function}`);
});
async callUpdateFunctionConfiguration(params) {
await this.provider.request('Lambda', 'updateFunctionConfiguration', params);
this.serverless.cli.log(`Successfully updated function: ${this.options.function}`);
}

updateFunctionConfiguration() {
async updateFunctionConfiguration() {
const functionObj = this.options.functionObj;
const serviceObj = this.serverless.service.serviceObject;
const providerObj = this.serverless.service.provider;
Expand Down Expand Up @@ -197,24 +186,23 @@ class AwsDeployFunction {
}

if ('role' in functionObj && !_.isObject(functionObj.role)) {
return this.normalizeArnRole(functionObj.role).then(roleArn => {
params.Role = roleArn;
const roleArn = await this.normalizeArnRole(functionObj.role);
params.Role = roleArn;

return this.callUpdateFunctionConfiguration(params);
});
await this.callUpdateFunctionConfiguration(params);
return;
} else if ('role' in providerObj && !_.isObject(providerObj.role)) {
return this.normalizeArnRole(providerObj.role).then(roleArn => {
params.Role = roleArn;

return this.callUpdateFunctionConfiguration(params);
});
const roleArn = await this.normalizeArnRole(providerObj.role);
params.Role = roleArn;
await this.callUpdateFunctionConfiguration(params);
return;
}

if (!Object.keys(_.omit(params, 'FunctionName')).length) {
return BbPromise.resolve();
return;
}

return this.callUpdateFunctionConfiguration(params);
await this.callUpdateFunctionConfiguration(params);
}

async deployFunction() {
Expand Down

0 comments on commit 84d423d

Please sign in to comment.