graphqlError.stack?.split is not a function - apollo

I have a response coming from a subgraph:
{
errors: [
{
errcode: '23505',
extensions: [Object],
message: 'duplicate key value violates unique constraint "company_name_idx"',
locations: [Array],
path: [Array],
stack: [Array]
},
{
detail: 'Key (company_id)=(2eef1fbe-e2c5-4180-a6ba-2d7dd75a7613) is not present in table "company".',
errcode: '23503',
extensions: [Object],
message: 'insert or update on table "companies_persons" violates foreign key constraint "companies_persons_company_id_fkey"',
locations: [Array],
path: [Array],
stack: [Array]
}
],
data: { createCompany: null, createCompaniesPerson: null },
http: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [Minipass], disturbed: true, error: null },
[Symbol(Response internals)]: {
url: 'http://host.docker.internal:8086/graphql',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0,
trailer: [Promise]
}
}
}
I checked this via:
didReceiveResponse: ({ response }) => {
console.log("RESPONSE");
console.log(response);
return response;
},
But the response that is being passed from the supergraph (latest versions of js ApolloGateway / ApolloServer) is:
{
"errors": [
{
"message": "graphqlError.stack?.split is not a function",
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"stacktrace": [
"TypeError: graphqlError.stack?.split is not a function",
" at enrichError (file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:42:57)",
" at file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:12:36",
" at Array.map (<anonymous>)",
" at normalizeAndFormatErrors (file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:10:33)",
" at formatErrors (file:///usr/src/app/node_modules/#apollo/server/dist/esm/requestPipeline.js:288:16)",
" at processGraphQLRequest (file:///usr/src/app/node_modules/#apollo/server/dist/esm/requestPipeline.js:175:19)",
" at processTicksAndRejections (node:internal/process/task_queues:96:5)",
" at async internalExecuteOperation (file:///usr/src/app/node_modules/#apollo/server/dist/esm/ApolloServer.js:573:16)",
" at async runHttpQuery (file:///usr/src/app/node_modules/#apollo/server/dist/esm/runHttpQuery.js:115:29)",
" at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/#apollo/server/dist/esm/httpBatching.js:34:16)"
]
}
},
{
"message": "graphqlError.stack?.split is not a function",
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"stacktrace": [
"TypeError: graphqlError.stack?.split is not a function",
" at enrichError (file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:42:57)",
" at file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:12:36",
" at Array.map (<anonymous>)",
" at normalizeAndFormatErrors (file:///usr/src/app/node_modules/#apollo/server/dist/esm/errorNormalize.js:10:33)",
" at formatErrors (file:///usr/src/app/node_modules/#apollo/server/dist/esm/requestPipeline.js:288:16)",
" at processGraphQLRequest (file:///usr/src/app/node_modules/#apollo/server/dist/esm/requestPipeline.js:175:19)",
" at processTicksAndRejections (node:internal/process/task_queues:96:5)",
" at async internalExecuteOperation (file:///usr/src/app/node_modules/#apollo/server/dist/esm/ApolloServer.js:573:16)",
" at async runHttpQuery (file:///usr/src/app/node_modules/#apollo/server/dist/esm/runHttpQuery.js:115:29)",
" at async runPotentiallyBatchedHttpQuery (file:///usr/src/app/node_modules/#apollo/server/dist/esm/httpBatching.js:34:16)"
]
}
}
],
"data": {
"createCompany": null,
"createCompaniesPerson": null
}
}
Checking the code... seems as though I can thwart this error by setting includeStacktraceInErrorResponses to false, but I want the stacktrace in development.

Related

checkSchema syntax documentation

I would like to use the checkSchema method instead of what I am currently doing with all the checks on the post route in an array. The problem I have is I can't find good documentation on the syntax used in the object for each key. The doc page for schema validation (https://express-validator.github.io/docs/schema-validation.html) gives one example but no links to all the syntax that defines all the attributes you can use (isInt, toInt, isUppercase, rtrim, etc.) I have searched high and low for the docs that tell you everything you can use there but no luck. Can someone point me in the right place?
express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.
you can find all the rules available in the link above.
here is a good example how it's used with checkSchema:
import { checkSchema, validationResult } from 'express-validator'
const schema = {
id: {
isFloat: true,
// Sanitizers can go here as well
toFloat: true,
errorMessage: "must be a valid number"
},
first_name: {
exists: {
errorMessage: "first_name is required"
},
isLength: {
errorMessage: "first_name has invalid length",
options: {
min: 1
}
}
},
middle_name: {
optional: {
options: { nullable: true, checkFalsy: true }
}
},
last_name: {
exists: {
errorMessage: "last_name is required"
},
isLength: {
errorMessage: "last_name has invalid length",
options: {
min: 1
}
}
},
date_of_birth: {
isISO8601: {
errorMessage: `date of birth is not a valid iso date`
},
isBefore: {
date: "01-01-2000",
errorMessage: `should be less than 01-01-2000`
},
isAfter: {
date: "01-01-1970",
errorMessage: `should be greater than 01-01-1970`
}
},
email: {
exists: {
errorMessage: "email is required"
},
isEmail: {
errorMessage: "email is invalid"
}
},
current_country_of_residence: {
exists: {
errorMessage: "current_country_of_residence is required",
options: {
checkNull: true,
checkFalsy: true
}
}
},
current_city_of_residence: {
exists: {
bail: true,
errorMessage: "current_city_of_residence is required"
},
isMongoId: {
errorMessage: "current_city_of_residence is has invalid id for"
}
},
email: {
isEmail: { errorMessage: 'email is not a valid email' },
isLength: { errorMessage: 'email has invalid length', options: { min: 1 } }
},
skills: {
isArray: {
errorMessage: `invalid value for skills`,
options: {
min: 3,
max: 5
}
},
isIn: {
options: ["java", "C++", "javascript"],
errorMessage: `allowed values for skills are: ${["java", "C++", "javascript"]}`
},
custom: {
options: (values) => {
const unique_values = new Set(values)
if (unique_values.size !== values.length) {
return Promise.reject()
}
return Promise.resolve()
},
errorMessage: `you can't add duplicated`
},
customSanitizer: {
options: async (value, { req }) => {
return value
}
}
}
}
const validate = () => {
return [
checkSchema(schema),
(req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() })
}
next()
}
]
}
export default validate()

Using sequelize with AWS Lambda

So I'm having some issues trying to use sequelize with AWS Lambda, when querying a table where id = 1 it sometimes returns me data and sometimes it doesn't. I read that Sequelize connections and AWS Lambda service don't get well each other because of the how Lambda executes a function.
My question is, is it not enough to open a connection at the top of a function and then close it at the bottom (before returning something)? If not, what else can I do?
Update:
const findCityByPk = async (pathParameters) => {
const { Postgresql: ps } = require('../libs/utils/potsgresql');
console.log(ps.connection.connectionManager);
const { id } = pathParameters;
try {
const city = await City.findByPk(id);
if (city) {
ps.connection.close();
return {
statusCode: 200,
body: JSON.stringify(city)
};
}
ps.connection.close();
return {
statusCode: 500,
body: JSON.stringify({ message: 'City not found`' })
};
} catch (err) {
console.log(err);
await ps.connection.close();
return {
statusCode: 500,
body: JSON.stringify(err)
};
}
}
This is the code I'm testing it sometimes returns me the correct object from my table
{"id":"1","city_name":"Lima2","zip_code":"12312","time_zone_utc":-5} -> this is what is supposed to be returning, and instead I'm getting this object
{
"requestTime": "06/Dec/2021:18:07:24 +0000",
"requestId": "8b5bf017-c180-41cc-9de6-b07599f0e9b8",
"apiId": "xx",
"resourceId": "xx",
"resourcePath": "/city/{id}",
"path": "/dev/city/1",
"httpMethod": "GET",
"status": "500",
"authLatency": "-",
"integrationLatency": "48",
"integrationStatus": "200",
"responseLatency": "50",
"responseLength": "2",
"errorMessage": "-",
"format": "SLS_ACCESS_LOG",
"version": "1.0.0"
}
And also, this is how it's being made the connection
const createConnection = () => {
console.info("[Postgresql] createConnection: start")
console.info("[Postgresql] createConnection: creating conection start")
let conn;
let string_connection;
try {
string_connection = `postgres://${config.DB_USER}:${config.DB_PASSWORD}#${config.DB_HOST}:5432/${config.DB_NAME}`
//console.debug(`[Postgresql] string_connection: ${string_connection}`)
conn = new Sequelize(string_connection, { logging: false, pool: { max: 1, min: 0, idle: 1000 } });
} catch (e) {
console.debug(`[Postgresql] createConnection: creating conection error ${string_connection}`)
throw e;
}
console.info("[Postgresql] createConnection:creating conection end")
return conn;
}

AWS - Cannot read property 'username' of undefined

I got an error: Cannot read property 'username' of undefined and also the const username will say that it is not used.
Complete Errror:
Response:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'username' of undefined",
"trace": [
"TypeError: Cannot read property 'username' of undefined",
" at Runtime.exports.handler (/var/task/index.js:7:50)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Code:
exports.handler = (event, context, callback) => {
console.log(event);
const connectionId = event.requestContext.connectionId;
const username = event.queryStringParameters.username;
addConnectionId(connectionId).then(() => {
callback(null, {
statusCode: 200,
});
});};
function addConnectionId(connectionId) {
const params = {
TableName: 'Chat',
Item: {
'connection_id' : connectionId,
'username' : username
}
};
return ddb.put(params).promise();
}
You need to enable Use Lambda Proxy integration to access query parameters.

lambda function outputted an error "e is not a function"

created two lambda functions by serverless-framework. first function "record-song-vote" writes DynamoDB, it works fine. second function "get-vote-counts" reads all records from DynamoDB, but it continually return error:
{
"errorType": "TypeError",
"errorMessage": "e is not a function",
"trace": [
"TypeError: e is not a function",
" at Runtime.handler (/var/task/serverless_sdk/index.js:9:131872)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
function get-vote-counts:
'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB.DocumentClient();
module.exports.handler = async event => {
const params = {
TableName: process.env.DYNAMODB_TABLE
};
const result = await dynamodb.scan(params, (error, data) => {
if (error) {
console.error("Unable to update item. Error JSON:", JSON.stringify(error, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
}).promise();
const outputData = result["Items"].map((item) => {
return {
songName: item['songName'],
votes: item['votes']
}
});
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(outputData)
}
};
I have tried to comment all line in this file. but I still got same error. does anybody have idea?

How do you query DynamoDB

I'm on Step 5.1 of "DynamoDB's Getting Started guide" http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.JsShell.05.html#GettingStarted.JsShell.05.01 and am blocked by a non-working example.
var params = {
TableName: "Music",
KeyConditionExpression: "Artist = :artist",
ExpressionAttributeValues: {
":artist": "No One You Know"
}
};
dynamodb.query(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});
The shell accepts the input but produces an Error
{
"message": "There were 2 validation errors:\n* MissingRequiredParameter: Missing required key 'KeyConditions' in params\n* UnexpectedParameter: Unexpected key 'KeyConditionExpression' found in params",
"code": "MultipleValidationErrors",
"errors": [
{
"message": "Missing required key 'KeyConditions' in params",
"code": "MissingRequiredParameter",
"time": "2015-10-27T03:08:56.504Z"
},
{
"message": "Unexpected key 'KeyConditionExpression' found in params",
"code": "UnexpectedParameter",
"time": "2015-10-27T03:08:56.504Z"
}
],
"time": "2015-10-27T03:08:56.504Z"
}
I tried sub'ing in 'KeyConditions' for 'ExpressionAttributeValues' like...
var params = {
TableName: "Music",
KeyConditionExpression: "Artist = :artist",
KeyConditions: {
":artist": "No One You Know"
}
};
dynamodb.query(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});
...but that just produces empty results {}. There are, of course, items in "Music" with the "Artist" attribute set to "No One You Know", so I'm kind-of lost how to proceed here.
What is the correct expression to query DDB for the value "No One You Know" in the Artist attribute?
The root cause of this is a stale "dynamodb-local" installation. brew upgrade dynamodb-local deployed a 2015-07-16_1.0 version of this kid and the query now works.