I'm currently learning AWS Lambda, and I'm trying to deploy a Lambda function whose inputs would be stored in a DynamoDB table(if that makes sense?), we were already given a source code to use and a separate code to test it.
I've checked both codes, refactored them, and started testing but somehow my results still return "failed" results. My code source is this:
const randomBytes = require('crypto').randomBytes;
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
const fleet = [
{
Name: 'Bucephalus',
Color: 'Golden',
Gender: 'Male',
},
{
Name: 'Shadowfax',
Color: 'White',
Gender: 'Male',
},
{
Name: 'Rocinante',
Color: 'Yellow',
Gender: 'Female',
},
];
exports.handler = (event, context, callback) => {
if (!event.requestContext.authorizer) {
errorResponse('Authorization not configured', context.awsRequestId, callback);
return;
}
const rideId = toUrlString(randomBytes(16));
console.log('Received event (', rideId, '): ', event);
// Because we're using a Cognito User Pools authorizer, all of the claims
// included in the authentication token are provided in the request context.
// This includes the username as well as other attributes.
const username = event.requestContext.authorizer.claims['cognito:username'];
// The body field of the event in a proxy integration is a raw string.
// In order to extract meaningful values, we need to first parse this string
// into an object. A more robust implementation might inspect the Content-Type
// header first and use a different parsing strategy based on that value.
const requestBody = JSON.parse(event.body);
const pickupLocation = requestBody.PickupLocation;
const unicorn = findUnicorn(pickupLocation);
recordRide(rideId, username, unicorn).then(() => {
// You can use the callback function to provide a return value from your Node.js
// Lambda functions. The first parameter is used for failed invocations. The
// second parameter specifies the result data of the invocation.
// Because this Lambda function is called by an API Gateway proxy integration
// the result object must use the following structure.
callback(null, {
statusCode: 201,
body: JSON.stringify({
RideId: rideId,
Unicorn: unicorn,
UnicornName: unicorn.Name,
Eta: '30 seconds',
Rider: username,
}),
headers: {
'Access-Control-Allow-Origin': '*',
},
});
}).catch((err) => {
console.error(err);
// If there is an error during processing, catch it and return
// from the Lambda function successfully. Specify a 500 HTTP status
// code and provide an error message in the body. This will provide a
// more meaningful error response to the end client.
errorResponse(err.message, context.awsRequestId, callback);
});
};
function findUnicorn(pickupLocation) {
console.log('Finding unicorn for ', pickupLocation.Latitude, ', ', pickupLocation.Longitude);
return fleet[Math.floor(Math.random() * fleet.length)];
}
function recordRide(rideId, username, unicorn) {
return ddb.put({
TableName: 'AWSIES-jeremie.agravante',
Item: {
RideId: rideId,
User: username,
Unicorn: unicorn,
UnicornName: unicorn.Name,
RequestTime: new Date().toISOString(),
},
}).promise();
}
function toUrlString(buffer) {
return buffer.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
function errorResponse(errorMessage, awsRequestId, callback) {
callback(null, {
statusCode: 500,
body: JSON.stringify({
Error: errorMessage,
Reference: awsRequestId,
}),
headers: {
'Access-Control-Allow-Origin': '*',
}
});
}
And the test code is this:
{
"path": "/ride",
"httpMethod ": "POST",
"headers": {
"Accept": "*/*",
"Authorization": "eyJraWQiOiJLTzRVMWZs",
"content-type": "application/json; charset=UTF 8"
},
"queryStringParameters ":"null",
"pathParameters ":"null",
"requestContext ": {
"authorizer": {
"claims": {
"cognito:username ": "the_username"
}
}
},
"body": "{\"PickupLocation \":
{\"Latitude\":47.6174755835663,\"Longitude\":-122.28837066650185}}"
}
The error that it throws me is this:
Test Event Name:testRequestEvent
Response
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Unexpected end of input",
"trace": [
"Runtime.UserCodeSyntaxError: SyntaxError: Unexpected end of input",
" at _loadUserApp (/var/runtime/UserFunction.js:98:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1072:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)",
" at Module.load (internal/modules/cjs/loader.js:937:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:778:12)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)",
" at internal/main/run_main_module.js:17:47"
]
}
Function Logs
START RequestId: 2f5c85af-632f-4fa2-8a32-46547e84fe64 Version: $LATEST
2021-11-18T01:39:55.279Z undefined ERROR Uncaught Exception
{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected end of
input","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected end of input"," at
_loadUserApp (/var/runtime/UserFunction.js:98:13)"," at Object.module.exports.load
(/var/runtime/UserFunction.js:140:17)"," at Object.<anonymous>
(/var/runtime/index.js:43:30)"," at Module._compile
(internal/modules/cjs/loader.js:1072:14)"," at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1101:10)"," at Module.load
(internal/modules/cjs/loader.js:937:32)"," at Function.Module._load
(internal/modules/cjs/loader.js:778:12)"," at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:76:12)"," at internal/main/run_main_module.js:17:47"]}
2021-11-18T01:39:56.826Z undefined ERROR Uncaught Exception
{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected end of input","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected end of input"," at _loadUserApp (/var/runtime/UserFunction.js:98:13)"," at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)"," at Object.<anonymous> (/var/runtime/index.js:43:30)"," at Module._compile (internal/modules/cjs/loader.js:1072:14)"," at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)"," at Module.load (internal/modules/cjs/loader.js:937:32)"," at Function.Module._load (internal/modules/cjs/loader.js:778:12)"," at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)"," at internal/main/run_main_module.js:17:47"]}
END RequestId: 2f5c85af-632f-4fa2-8a32-46547e84fe64
REPORT RequestId: 2f5c85af-632f-4fa2-8a32-46547e84fe64 Duration: 1714.81 ms Billed
Duration: 1715 ms Memory Size: 128 MB Max Memory Used: 12 MB
Unknown application error occurred
Runtime.UserCodeSyntaxError
Request ID
2f5c85af-632f-4fa2-8a32-46547e84fe64
I'm sorry if this is really long, but I could really use a hand in this one. I keep looking for syntax errors even found some bugs that my instructors have purposely snuck in to test us, but I guess my beginner skills are not enough at the moment. Thanks to anyone who could help.
I've tried to set up an API gateway and IAM permission but I keep getting an error message when I test my lambda function.
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Cannot use import statement outside a module",
"trace":
"Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
" at _loadUserApp (/var/runtime/UserFunction.js:98:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1138:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)",
" at Module.load (internal/modules/cjs/loader.js:986:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:879:14)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)",
" at internal/main/run_main_module.js:17:47"
My lambda function:
import * as AWS from 'aws-sdk';
AWS.config.update({
accessKeyId: 'key',
secretAccessKey: 'key',
region: 'us-east-1'
});
const documentClient: AWS.DynamoDB.DocumentClient = new AWS.DynamoDB.DocumentClient();
interface IEvent {
email: string;
firstName: string;
lastName: string;
}
exports.handler = async (event: IEvent): Promise<void> => {
if (!event.email) {
throw new Error('Candidate email is required.');
}
if (!event.firstName) {
throw new Error('Candidate first name is required.');
}
if (!event.lastName) {
throw new Error('Candidate last name is required.');
}
await documentClient.put({
TableName: 'honeypot-interview-contacts',
Item: event
}).promise();
};
You've got the error right there, actually: SyntaxError: Cannot use import statement outside a module. Try switching to require? And it looks like you're running TypeScript? I don't think the default Node runtime has built in support for TS, you might want to run the code through the TS compiler first, that should also handle the import error.
i am making mocha test cases. but when i am running my file giving error. this my error.
TypeError: Cannot set property 'files' of undefined
this is my code
const describe = require('mocha');
const assert = require('assert');
describe('Array', () => {
describe('#indexOf()', () => {
it('should return -1 when the value is not present', () => {
// assert.equal([1, 2, 3].indexOf(4), -1);
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
this is error
E:\Node\Angular-node-mysql\server\node_modules\mocha\lib\mocha.js:85
this.files = [];
^
TypeError: Cannot set property 'files' of undefined
at Mocha (E:\Node\Angular-node-mysql\server\node_modules\mocha\lib\mocha.js:85:14)
at Object.<anonymous> (E:\Node\Angular-node-mysql\server\routes\userRoute\user.spec.js:5:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
you should use require mocha first then define describe from mocha
let mocha = require('mocha');
let describe = mocha.describe;
as Gribbs comment here
https://github.com/mochajs/mocha/issues/2314#issuecomment-387944573
I'm using Ruby sass with PostCSS. This is my gulp css task.
gulp.task('css', function () {
var processors = [
short,
rucksack,
postcssmodules
];
return gulp.src('./css/src/*.scss')
.pipe(postcss(processors, {syntax: scss}))
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dest'));
});
Error I'm getting
➜ website git:(master) ✗ gulp css
[09:52:08] Using gulpfile ~/my-projects/website/gulpfile.js
[09:52:08] Starting 'css'...
[09:52:08] 'css' errored after 12 ms
[09:52:08] Error: must provide pattern
at new GlobSync (/Users/jitendravyas/my-projects/website/node_modules/glob/sync.js:29:11)
at Function.globSync [as sync] (/Users/jitendravyas/my-projects/website/node_modules/glob/sync.js:24:10)
at /Users/jitendravyas/my-projects/website/node_modules/gulp-ruby-sass/index.js:68:21
at Array.forEach (native)
at gulpRubySass (/Users/jitendravyas/my-projects/website/node_modules/gulp-ruby-sass/index.js:67:10)
at /Users/jitendravyas/my-projects/website/gulpfile.js:48:15
at taskWrapper (/Users/jitendravyas/my-projects/website/node_modules/undertaker/lib/set-task.js:13:15)
at bound (domain.js:287:14)
at runBound (domain.js:300:12)
at asyncRunner (/Users/jitendravyas/my-projects/website/node_modules/async-done/index.js:36:18)
You cannot use gulp-ruby-sass in a .pipe(). Read the docs:
Use gulp-ruby-sass instead of gulp.src to compile Sass files.
You'll have to use sass() before your postcss():
gulp.task('css', function() {
var processors = [
short,
rucksack,
postcssmodules
];
return sass('./css/src/*.scss')
.on('error', sass.logError)
.pipe(postcss(processors))
.pipe(gulp.dest('./dest'));
});
I have my gulpfile.coffee
gulp = require 'gulp'
coffeelint = require 'gulp-coffeelint'
mocha = require 'gulp-mocha'
plumber = require 'gulp-plumber'
gutil = require 'gulp-util'
watch = require 'gulp-watch'
handleError = (err) ->
console.error err.message
process.exit 1
gulp.task 'test', ->
gulp.src('test/*-test.*')
.pipe(mocha(reporter: 'spec'))
.on 'error', handleError
I need run gulp test --grep group1, i found options.grep but i don't know how proceed parameter from CLI.
SOLVED: using yargs npm package
gulp = require 'gulp'
coffeelint = require 'gulp-coffeelint'
mocha = require 'gulp-mocha'
plumber = require 'gulp-plumber'
gutil = require 'gulp-util'
watch = require 'gulp-watch'
yargs = require 'yargs'
handleError = (err) ->
console.error err.message
process.exit 1
gulp.task 'test', ->
gulp.src('test/*-test.*')
.pipe(mocha(reporter: 'spec', grep: yargs.argv.grep))
.on 'error', handleError