can't add fields in friend's dynamodb using lambda - aws-lambda

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.

Related

RXJS 7.5.5 WebSocket is not defined

I attempt to get a websocket in a Next.js app.
I'm getting an Error and I'm not sure if it is a Bug in RxJS or if there's something wrong in my setup.
The Error Message:
ReferenceError: WebSocket is not defined
at new WebSocketSubject (/myApp/node_modules/rxjs/dist/cjs/internal/observable/dom/WebSocketSubject.js:63:42)
at Object.webSocket (/myApp/node_modules/rxjs/dist/cjs/internal/observable/dom/webSocket.js:6:12)
at eval (webpack-internal:///./pages/_app.tsx:19:61)
at ./pages/_app.tsx (/myApp/.next/server/pages/_app.js:22:1)
at __webpack_require__ (/myApp/.next/server/webpack-runtime.js:33:42)
at __webpack_exec__ (/myApp/.next/server/pages/_app.js:64:39)
at /myApp/.next/server/pages/_app.js:65:28
at Object.<anonymous> (/myApp/.next/server/pages/_app.js:68:3)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
The code at WebSocketSubject.js:63
if (!config.WebSocketCtor && WebSocket) {
config.WebSocketCtor = WebSocket;
}
I wasn't able to find these two variables defined anywhere - not sure if that's the matter, or if these arrive in a fancy JS way.
When changing WebSocket to webSocket it doesn't help either (that was an assumption as I was able to see a difference in my code below.
// nextauth
import './styles.css';
import * as rxws from 'rxjs/webSocket';
console.log('websocket as own import', rxws);
//websocket as own import { webSocket: [Getter], WebSocketSubject: [Getter] }
console.log('websocket lowercase', rxws.webSocket);
//websocket lowercase [Function: webSocket]
console.log('websocket uppercase', rxws.WebSocket);
//websocket uppercase undefined
const socket$ = rxws.webSocket(
"ws://ws.ifelse.io"
);
function App({ Component, pageProps }: AppProps): JSX.Element {
return (
<div>
Hello
</div>
);
}
export default App;
parts of package.json
"next": "^11.0.0",
"redux-observable": "^2.0.0",
"rxjs": "^7.5.5",
"ws": "^8.7.0"
What's your 2ct on that?

AWS Lambda test run failure

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.

Ethereum Mocha Terminal Error - "Error: Cannot find module 'randomhex' "

I'm currently taking this udemy course on developing networks on Ethereum. The course was made two years ago so I sort of have to use old versions of everything to follow through. My code would run just fine when performing "npm run test" but after adding the statement in line 29 (the assert.ok statement), I started getting this error. I don't understand what is the terminal error. Help?
inbox.test.js:
//inbox.test.js
const assert = require('assert'); // used for ganache assertion
const ganache = require('ganache-cli'); // local ethereum testing netwrok
const Web3 = require('web3'); // Web3 is a constructor function (that's why it is capatalized)
const { interface, bytecode } = require('../compile'); // descructors - going up the directory tree
// creating an instance of Web3
const provider = ganache.provider();
const web3 = new Web3(provider);
let accounts; // to be accessed globally
let inbox; // holds the deployed contract
beforeEach( async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts(); //eth is a module that has a lot of functions used for development
// Use one of the accounts to deploy the contract
inbox = await new web3.eth.Contract (JSON.parse(interface)) // instance of a contract
.deploy({data: bytecode, arguments: ['Hi There!'] })
.send ({from: accounts[0], gas:'1000000'});
inbox.setProvider(provider);
});
describe('Inbox', ()=> {
it('deployes a contract', () => {
assert.ok(inbox.options.address); // to check if the contract is successfuly depolyed
});
it('has a default message', async () => {
const message = await inbox.methods.message().call();
assert.equal(message, 'Hi there!');
});
it('can change the message', async () => {
await inbox.methods.setMessage('bye').send( {from: accounts[0]} );const message = await inbox.methods.message().call();
assert.equal(message, 'bye');
});
});
Terminal error:
Terminal Error 1
Terminal Error 2
Package.json:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"author": "Eiman",
"license": "ISC",
"dependencies": {
"ganache-cli": "^6.9.1",
"mocha": "^8.1.0",
"solc": "^0.4.17",
"web3": "^1.0.0-beta.26"
}
}
compile.js:
// Modules
const path = require ('path'); // module used to help build a path from compile.js to inbox.sol - guaranteed to get compatibility with OS used
const fs = require ('fs');
const solc = require ('solc');
const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol' );
const source = fs.readFileSync(inboxPath, 'utf8'); // to read the content of the inbox.sol file
module.exports = solc.compile(source, 1).contracts[':Inbox']; // compile statement
inbox.sol:
pragma solidity ^0.4.17;
contract Inbox {
string public message;
function Inbox (string initalMessage) public {
message = initalMessage;
}
function setMessage(string newMessage) public {
message = newMessage;
}
}
Your code runs smoothly on my Mac (the strings are actually different):
Inbox
✓ deployes a contract
1) has a default message
✓ can change the message (74ms)
2 passing (405ms)
1 failing
1) Inbox
has a default message:
AssertionError [ERR_ASSERTION]: 'Hi There!' == 'Hi there!'
+ expected - actual
-Hi There!
+Hi there!
Looks like some problem with your node_modules, try a fresh install.

Failed: Cannot read property 'saveFullPageScreen' of undefined

I came across protractor-image-comparison and wanted to test it out.
I made a limited test based on the example of the website, and I get the error
Failed: Cannot read property 'saveFullPageScreen' of undefined.
The browser.imageComparison is not defined.
It's strange I get this error following the example. There is limited support for protractor so I ask it here.
----------------- test.spec.ts --------------
import { browser, } from 'protractor';
import { Urls, DashboardPage } from '../utils';
fdescribe('protractor-image-comparison desktop', () => {
beforeEach(async () => {
await Urls.gotoDashboard();
await DashboardPage.getVPoints();
// await DashboardPage.removeDebugInfo();
});
it('should save some screenshots', async() => {
// Save a full page screens
await .saveFullPageScreen('fullPage', { /* some options*/ });
});
it('should compare successful with a baseline', async() => {
// Check a full page screens
expect(await browser.imageComparison.checkFullPageScreen('fullPage', { /* some options*/ })).toEqual(0);
});
});
-------------- part of jasmine.ts ---------------
plugins: [
{
// The module name
package: 'protractor-image-comparison',
// Some options, see the docs for more
options: {
baselineFolder: join(process.cwd(), './baseline/'),
formatImageName: `{tag}-{logName}-{width}x{height}`,
screenshotPath: join(process.cwd(), '.tmp/'),
savePerInstance: true,
autoSaveBaseline: true,
blockOutToolBar: true,
clearRuntimeFolder: true,
// ... more options
},
},
],
Failures:
1) protractor-image-comparison desktop should save some screenshots
Message:
Failed: Cannot read property 'saveFullPageScreen' of undefined
Stack:
TypeError: Cannot read property 'saveFullPageScreen' of undefined
at Object.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:119:83)
at step (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:75:27)
at Object.next (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:24:53)
at c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:17:71
at new Promise (<anonymous>)
at __awaiter (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:3:12)
at UserContext.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:110:16)
at c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:112:25
at new ManagedPromise (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:1077:7)
at ControlFlow.promise (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2505:12)
From: Task: Run it("should save some screenshots") in control flow
at UserContext.<anonymous> (c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:94:19)
at c:\projects\vital10-frontend\node_modules\jasminewd2\index.js:64:48
at ControlFlow.emit (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\events.js:62:21)
at ControlFlow.shutdown_ (c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2674:10)
at c:\projects\vital10-frontend\node_modules\selenium-webdriver\lib\promise.js:2599:53
From asynchronous test:
Error
at Suite.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:109:5)
at Object.<anonymous> (c:\projects\vital10-frontend\e2e\jasmine\image_compair\test.spec.ts:93:1)
at Module._compile (internal/modules/cjs/loader.js:868:30)
at Module.m._compile (c:\projects\vital10-frontend\node_modules\ts-node\src\index.ts:392:23)
at Module.m._compile (c:\projects\vital10-frontend\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (internal/modules/cjs/loader.js:879:10)
According to the docs you are missing browser.imageComparison before .saveFullPageScreen

React Native crash when register exist user by RxJS ajax

I am register new strapi user by RxJS ajax. When user already exist, I expect the 'user already exist' return but It crash my app.
Unhandled JS Exception: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
How to handle error with RxJS ajax?
import { ajax } from "rxjs/ajax";
import { map, catchError } from "rxjs/operators";
const testAjax = () => {
const test$ = ajax({
url: "http://localhost:1337/auth/local/register",
method: "POST",
body: {
username: "email3#test.com",
email: "email3#test.com",
password: "password"
}
})
.pipe(
map(userResponse => userResponse),
catchError(error => console.log("Error: ", error))
)
.subscribe(({ response }) => {
console.log("res: ", response);
});
};
did you try console userResponse , map(userResponse => console.log('users: ', userResponse)), may be there was the reason for the crash

Resources