serverless framework with json parsing error - javascript

I use serverless framework with javascript.
my code is:
import { App } from '../lib/App';
export const hello = (event, context, cb) => {
context.callbackWaitsForEmptyEventLoop = false;
// This resolved promise would be be in the application library code in a real-world application and provide the results
App.handleFirst(event) // eslint-disable-line promise/catch-or-return
.then(result => ({
statusCode: 200,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(result)
}))
.asCallback(cb);
return;};
inside App.js
import BbPromise from 'bluebird';
const THE_MESSAGE = 'Hello from the webpack 4 sample';
export class App {
static handleFirst(event) {
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
console.info(myDemoResult);
return BbPromise.resolve(myDemoResult);
}
I use fellow command to deploy it.
set SLS_DEBUG=*
severless deploy
my error is:
Syntax Error -------------------------------------------
Unexpected token A in JSON at position 0
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Stack Trace --------------------------------------------
SyntaxError: Unexpected token A in JSON at position 0
SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
at BbPromise.try (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:47)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Function.Promise.attempt.Promise.try (F:\workspace\svlecma\node_modules\bluebird\js\release\method.js:39:29)
at Utils.spawnProcess.catch.then.then.depJson (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:35)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:17:14)
From previous event:
at PluginManager.invoke (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:390:22)
at PluginManager.spawn (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:408:17)
at ServerlessWebpack.BbPromise.bind.then.then.then (F:\workspace\svlecma\node_modules\serverless-webpack\index.js:102:51)
at runCallback (timers.js:694:18)
at tryOnImmediate (timers.js:665:5)
at processImmediate (timers.js:647:5)
at process.topLevelDomainCallback (domain.js:121:23)
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com
Your Environment Information -----------------------------
OS: win32
Node Version: 10.10.0
Serverless Version: 1.31.0
my serverless.yml is here:
https://gist.github.com/thinksource/9fd0c8728df2195b7110b3be04aec2ae
why json first element error? how Can I see the json string?

After seeing your serverless.yml file, I believe that the issue may well be in the webpack.config.js file. It may be worth trying changing your custom section, and putting quotes around: 'webpack.config.js'. Like:
custom:
webpack:
webpackConfig: 'webpack.config.js'
includeModules: true
I think that the issue is in your App.js class here:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
You have a invalid JSON structure; where the object event is being passed, it is not being given a key/name. You probably want something like:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event: event
};
Also your constant THE_MESSAGE is not inside your App class. You should move it inside the App classes {..} like this:
export class App {
static get THE_MESSAGE() { return 'Hello from the webpack 4 sample'; }
...

Related

Intellij Idea ReferenceError: is not defined

When debugging typescript code from my testcases in Intellij Idea I get the following error inside the Evaluate window (Alt + F8):
ReferenceError: InternalServerException is not defined
at eval (eval at getStatusCodeAndResponse (C:\Users\<user>\Documents\Projecten\stations-api\app\common\error-handler.ts:17:13), <anonymous>:1:1)
at Object.getStatusCodeAndResponse (C:\Users\<user>\Documents\Projecten\stations-api\app\common\error-handler.ts:17:13)
at Lambda.handler (C:\Users\<user>\Documents\Projecten\stations-api\app\get-guiding-lines-combinations.ts:38:20)
at Lambda.<anonymous> (C:\Users\<user>\Documents\Projecten\stations-api\node_modules\#aws-lambda-powertools\metrics\src\Metrics.ts:277:41)
at Lambda.<anonymous> (C:\Users\<user>\Documents\Projecten\stations-api\node_modules\#aws-lambda-powertools\logger\src\Logger.ts:337:41)
at Lambda.<anonymous> (C:\Users\<user>\Documents\Projecten\stations-api\node_modules\#aws-lambda-powertools\tracer\src\Tracer.ts:364:33)
at Object.<anonymous> (C:\Users\<user>\Documents\Projecten\stations-api\app\get-guiding-lines-combinations.test.ts:41:41)
at Promise.then.completed (C:\Users\<user>\Documents\Projecten\stations-api\node_modules\jest-circus\build\utils.js:391:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (C:\Users\<user>\Documents\Projecten\stations-api\node_modules\jest-circus\build\utils.js:316:10)
The way I import my custom class:
import {
BadRequestException,
Exception,
InternalServerException,
NotFoundException,
} from '../models/Exceptions';
The custom class itself:
export class InternalServerException implements Error {
message: string;
name: string = 'InternalServer';
statusCode: number = 500;
constructor(message?: string) {
this.message = message ?? 'Internal server exception';
}
createResponse(): APIGatewayProxyStructuredResultV2 {
return {
statusCode: this.statusCode,
body: this.message,
};
}
}
While it can easely find my custom classes etc when running the tests. How can I get my classes recognized inside the evaluate window? Since this makes debugging a lot easier. (The version I am using is Intellij Idea 2022.3.2 ultimate)

Using Edge.js in Typescript to call an API

This is my first time using Angular, Edge.js or calling an API. I'm not sure if I'm doing things right, but I'm surely doing something wrong because it's not working.
To get the data from the API written in C# I'm using Edge.js in a service in my Angular project.
data.service.ts:
import { Injectable, ValueProvider } from '#angular/core';
import * as edge from "edge";
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor() { }
getData(type: string, method: string) {
let data = edge.func({
assemblyFile: 'C:\Program Files\Common Files\Siemens\Automation\Simatic OAM\bin\CC.CommonInterfaces.dll',
typeName: `CC.CommonInterfaces.${type}`,
methodName: `${method}`
});
return data(null, function(error, result) {
if (error) throw error;
console.log(result);
return result;
});
}
}
Then I'm simply calling the getData method with the right parameters in a component like this:
onClickTestAPI() {
this.dataSrv.getData("IState", "IsTunnelActive");
}
But when running the web server, the console output shows this:
core.js:4002 ERROR Error: Uncaught (in promise): Error: Unexpected token '<'
Evaluating https://localhost:8888/edge
Loading ccui/ccui.umd.js
SyntaxError: Unexpected token '<'
at eval (<anonymous>)
at Qe (system.js:4)
at system.js:4
at T (system.js:4)
at T.h (system.js:4)
at T (system.js:4)
at system.js:4
at system.js:4
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.js:26255)
at resolvePromise (zone.js:852)
at zone.js:762
at rejected (tslib.es6.js:69)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.js:26255)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
at zone.js:910
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:26246)
There isn't even an API response (or at least I can't find it).
Any idea where I went wrong?

Storing global variable in a separate file for Protractor Tests

I am trying to create a separate inventory file for Protractor Test where I can store all the reusable variable to be used by different test scrips. The sample Variable list is called Vars.js and the specs should import the variables from this file and consume those. However, this fails as shown below. Can this approach actually be used for storing reusable variables? Can I actually create a separate inventory file for protractor tests outside of conf.js?
Vars.js has the following content :
"use strict";
exports.config = {
function() {
global.loginMain = 'https://mytestsite.com/auth/login';
global.TestText = 'I am the test Text';
}
};
and the spec file is as follows:
require ('./Vars.js')
require('..\\waitAbsent.js')
require("../node_modules/jasmine-expect/index.js")
describe('Vairables Import Test', function() {
console.log(global.loginMain);
console.log(global.TestText);
browser.get(global.loginMain);
it('Text Validation', function(){
expect(browser.getCurrentUrl()).toEqual('https://mytestsite.com/auth/login')
})
});
The log
[10:55:29] I/local - Selenium standalone server started at http://192.168.1.187:51256/wd/hub
undefined
undefined
Started
(node:17800) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods
instead.
F
Failures:
1) Vairables Import Test encountered a declaration exception
Message:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
Stack:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
at Url.parse (url.js:152:11)
at urlParse (url.js:146:13)
at Url.resolve (url.js:661:29)
at Object.urlResolve [as resolve] (url.js:657:40)
at ProtractorBrowser.get (C:\FCPS_I\FCPS\node_modules\protractor\built\browser.js:653:17)
at Suite.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:10:13)
at Object.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:5:1)
1 spec, 1 failure
Update: a revised Vars.js where I used params as shown below also return the same failure.
"use strict";
exports.config = {
params: {
loginMain: 'https://dss-esy.insystechinc.com/auth/login',
TestText : 'I am the test Text',
}
};
The below approach should work for you.
conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['app.js'],
onPrepare: async() => {
global.globalVariables = require('./globalVariables');
}
};
app.js
describe('desribe the test', () => {
it('the it', async () => {
console.log(globalVariables.loginMain);
console.log(globalVariables.TestText);
})
})
globalVariables.js
module.exports = {
loginMain :'https://mytestsite.com/auth/login',
TestText : 'I am the test Text'
}

How to correctly configure unit tests for Probot with Scheduler Extension?

I am using the following minimal probot app and try to write Mocha unit tests for it.
Unfortunately, it results in the error below, which indicates that some of my setup for the private key or security tokens is not picked up.
I assume that the configuration with my .env file is correct since I do not get the same error when I start the probot via probot-run.js.
Are there any extra steps needed to configure probot when used with Mocha?
Any suggestions on why the use of the scheduler extension may result in such issue would be great.
Code and error below:
app.ts
import createScheduler from "probot-scheduler";
import { Application } from "probot";
export = (app: Application) => {
createScheduler(app, {
delay: !!process.env.DISABLE_DELAY, // delay is enabled on first run
interval: 24 * 60 * 60 * 1000 // 1 day
});
app.on("schedule.repository", async function (context) {
app.log.info("schedule.repository");
const result = await context.github.pullRequests.list({owner: "owner", repo: "test"});
app.log.info(result);
});
};
test.ts
import createApp from "../src/app";
import nock from "nock";
import { Probot } from "probot";
nock.disableNetConnect();
describe("my scenario", function() {
let probot: Probot;
beforeEach(function() {
probot = new Probot({});
const app = probot.load(createApp);
});
it("basic feature", async function() {
await probot.receive({name: "schedule.repository", payload: {action: "foo"}});
});
});
This unfortunately results in the following error:
Error: secretOrPrivateKey must have a value
at Object.module.exports [as sign] (node_modules/jsonwebtoken/sign.js:101:20)
at Application.app (node_modules/probot/lib/github-app.js:15:39)
at Application.<anonymous> (node_modules/probot/lib/application.js:260:72)
at step (node_modules/probot/lib/application.js:40:23)
at Object.next (node_modules/probot/lib/application.js:21:53)
Turns out that new Probot({}); as suggested in the documentation initializes the Probot object without any parameters (the given options object {} is empty after all).
To avoid the error, one can provide the information manually:
new Probot({
cert: "...",
secret: "...",
id: 12345
});

Undefined not a function -- Meteor Smart Package

Recently, I've been trying to work on a smart package for a project I'm working on, and I'm having a problem.
The following code lives inside server/methods.js:
Meteor.startup(function() {
Meteor.methods({
// ISBN Lookup for AWS
isbnAWS: function(isbn) {
OperationHelper = apac.OperationHelper;
isbn = isbn.replace(/-/g,"");
console.log("Looking up ISBN: " + isbn);
cachedBook = BookCache.findOne({"isbn": isbn});
// If the book isn't in cache, use apac to get information into cache.
if (!cachedBook) {
// Instantiate the OH object for APAC.
OpHelper = new OperationHelper({
awsId: AWS_KEY_ID,
awsSecret: AWS_SECRET_KEY,
assocId: AWS_ASSOC_ID
});
// Use OH to query AWS, synchronously.
result = OpHelper.executeSync({
SearchIndex: 'Books',
ResponseGroup: 'Medium,Images',
IdType: 'ISBN',
ItemId: isbn
});
console.log(result);
} else {
console.log("Using cache for ISBN: " + isbn);
}
}
});
});
This method is being called by an event handler in a project template, as such:
"click #isbn-btn": function() {
// Store the current ISBN in Session, for reactivity.
theISBN = $("#isbn").val().trim().replace(/-/g, "");
Session.set("aws-isbn", theISBN);
// Make a call to our Meteor.method, which will contact AWS, and give us
// a result.
Meteor.call("isbnAWS", theISBN, function(err, res) {
if (err)
console.log("Error: " + err);
else
console.log("Success!");
});
}
OperationHelper is part of the package I have written, which contains this code, inside the package's lib/meteor-apac.js:
if (!Meteor.isClient) {
apac = Npm.require("apac-czbaker");
OperationHelper = apac.OperationHelper;
function makeSyncMethod(method){
var wrapped=Meteor._wrapAsync(method);
var syncMethod=function(){
return wrapped.apply(this,arguments);
};
return syncMethod;
}
OperationHelper.prototype.executeSync = makeSyncMethod(OperationHelper.prototype.execute);
}
And this is my package.js, where the apac object is clearly exported for use in my project:
Package.describe({
summary: "Access to the Amazon Product Advertising API, using the NodeJS 'apac' module.",
version: "0.0.4",
git: "https://github.com/czbaker/meteor-apac.git",
name: "czbaker:apac"
});
Npm.depends({
"apac-czbaker": "1.0.0"
});
Package.onUse(function(api) {
api.versionsFrom('METEOR#0.9.0.1');
api.use('underscore', 'server');
api.addFiles('lib/meteor-apac.js');
api.export('apac');
});
For some reason, I get the following output when I try to use the executeSync() function that I attempt to add using my package:
I20140831-15:16:56.651(-4)? Looking up ISBN:
W20140831-15:16:56.826(-4)? (STDERR)
W20140831-15:16:56.826(-4)? (STDERR) events.js:72
W20140831-15:16:56.827(-4)? (STDERR) throw er; // Unhandled 'error' event
W20140831-15:16:56.827(-4)? (STDERR) ^
W20140831-15:16:56.831(-4)? (STDERR) TypeError: undefined is not a function
W20140831-15:16:56.831(-4)? (STDERR) at /home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/lib/OperationHelper.js:85:17
W20140831-15:16:56.832(-4)? (STDERR) at Parser.<anonymous> (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:384:20)
W20140831-15:16:56.832(-4)? (STDERR) at Parser.emit (events.js:95:17)
W20140831-15:16:56.832(-4)? (STDERR) at Object.onclosetag (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:348:26)
W20140831-15:16:56.832(-4)? (STDERR) at emit (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:615:33)
W20140831-15:16:56.833(-4)? (STDERR) at emitNode (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:620:3)
W20140831-15:16:56.833(-4)? (STDERR) at closeTag (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:861:5)
W20140831-15:16:56.834(-4)? (STDERR) at Object.write (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:1294:29)
W20140831-15:16:56.834(-4)? (STDERR) at Parser.exports.Parser.Parser.parseString (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:403:31)
W20140831-15:16:56.834(-4)? (STDERR) at Parser.parseString (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:6:61)
=> Exited with code: 8
=> Your application is crashing. Waiting for file change.
From what I gather, it seems like it's trying to say that executeSync isn't a function, but...it clearly is. I'm very confused. I have no idea what I'm doing wrong here. Any thoughts would be greatly appreciated.
OperationHelper.prototype.execute takes 3 arguments function(operation, params, callback)
Meteor._wrapAsync just tacks on an extra argument as a callback
You only provide 1 argument to OpHelper.executeSync
The net result is the "automatic" callback provided by Meteor._wrapAsync is being passed as the second paarameter params rather than as the 3rd parameter "callback".
Change your server/method.js to provide an empty params to the function, and you should be fine. eg:
result = OpHelper.executeSync({
SearchIndex: 'Books',
ResponseGroup: 'Medium,Images',
IdType: 'ISBN',
ItemId: isbn
}, {});

Categories

Resources