redisClient.set :- no update no error - heroku

redisClient.get('abc', function(err, abcValue){
console.log(abcValue);
abcValue = abcValue + 'id';
redisClient.set('abc', abcValue, function(err){
console.log('abc updated');
});
});
nested updation over network, prints 'abc updated', but actual value does not update in redis database.
Note:- the above code works on localhost, but update not showing on heroku-redistogo.
Edit:- I'm running code on localhost, with redis connected to Redistogo. Using the following code:-
Setting up of express session:-
app.use(express.session({
store: new RedisStore({
host: 'birdeye.redistogo.com',
port: 1384,
db: 'redistogo',
pass: '052940128c2f2452f73378588dd5fb129'
}),
secret: '1234567890QWERTY',
}));
I am also creating another redisClient using the following code:-
var redisClient = require('redis').createClient( 1384, 'birdeye.redistogo.com', {detect_buffers: true});
redisClient.auth('052940128c2f2452f73378588dd5fb129', function() {
console.log('Redis client connected');
});

Do you see abc updated inside the console when running this code on Heroku ? It seems to be a misconfiguration of Redis client.

Related

sveltekit/vite problem with self signed certificate on localhost

In my dev environment I'm using the basicSsl-Plugin for generating a self-signed-certificate. The website works fine under https until the fetch function is trying to delete a user.
my vite.config.js:
plugins: [
basicSsl(),
sveltekit(),
{
name: 'sveltekit-socket-io',
configureServer(server) {
const io = new Server(server.httpServer);
io.on('connection', (socket) => {
const agent = new https.Agent({
rejectUnauthorized: false
});
socket.on('disconnect', () => {
await fetch('https://localhost:5173/api/users', {
method: 'DELETE',
body: JSON.stringify({ id: socket.uid }),
agent: agent
});
});
});
i get the error Error: self-signed certificate and code DEPTH_ZERO_SELF_SIGNED_CERT.
when instead of using the basicSsl-Plugin I try using using mkcert-created self signed certificates I cant even access the website anymore with https because I get the following error in the browser: ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
I added process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; and now it seems to work. I guess it's fine for development purposes, don't use it on production.

Unable to query dynamodb GSI in lambda locally

So I added a lambda function category using the amplify CLI, in order to query data from the GSI(Global secondary Index) I created using the #key directive in the graphql schema. Whenever I try mocking the function locally using the amplify mock function <functionName> the callback function of the query keeps on returning null. The function can be seen below
const AWS = require("aws-sdk");
const db = new AWS.DynamoDB.DocumentClient({
region: process.env.REGION,
apiVersion: "2012-08-10",
});
const params = {
// ProjectionExpression: ["province", "gender", "updatedAt", "createdAt"],
ExpressionAttributeValues: {
":provinceVal": "Sichuan",
},
IndexName: "RegistreesByProvince",
KeyConditionExpression: "province = :provinceVal",
TableName: process.env.API_PORTAL_SUBMISSIONSTABLE_NAME,
};
const calculateStatistics = async () => {
try {
const data = await db.query(params).promise();
console.log(data);
} catch (err) {
console.log(err);
}
};
const resolvers = {
Query: {
getStatistics: () => {
return calculateStatistics();
},
},
};
exports.handler = async (event) => {
// TODO implement
const typeHandler = resolvers[event.typeName];
if (typeHandler) {
const resolver = typeHandler[event.fieldName];
if (resolver) {
var result = await resolver(event);
return result;
}
}
}; // };
I then tried to capture the whole event and logged it to the console as can be seen in the calculateStatistics function, which now showed me a bit more explicit error as follows.
{ UnknownEndpoint: Inaccessible host: `dynamodb.us-east-1-fake.amazonaws.com'. This service may not be available in the `us-east-1-fake' region.
at Request.ENOTFOUND_ERROR (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/event_listeners.js:501:46)
at Request.callListeners (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at Request.emit (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
at Request.emit (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/request.js:688:14)
at ClientRequest.error (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/event_listeners.js:339:22)
at ClientRequest.<anonymous> (/Users/apple/Documents/work/web/portal/amplify/backend/function/calcStatistics/src/node_modules/aws-sdk/lib/http/node.js:96:19)
at ClientRequest.emit (events.js:198:13)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at TLSSocket.emit (events.js:198:13)
message:
'Inaccessible host: `dynamodb.us-east-1-fake.amazonaws.com\'. This service may not be available in the `us-east-1-fake\' region.',
code: 'UnknownEndpoint',
region: 'us-east-1-fake',
hostname: 'dynamodb.us-east-1-fake.amazonaws.com',
retryable: true,
originalError:
{ Error: getaddrinfo ENOTFOUND dynamodb.us-east-1-fake.amazonaws.com dynamodb.us-east-1-fake.amazonaws.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
message:
'getaddrinfo ENOTFOUND dynamodb.us-east-1-fake.amazonaws.com dynamodb.us-east-1-fake.amazonaws.com:443',
errno: 'ENOTFOUND',
code: 'NetworkingError',
syscall: 'getaddrinfo',
hostname: 'dynamodb.us-east-1-fake.amazonaws.com',
host: 'dynamodb.us-east-1-fake.amazonaws.com',
port: 443,
region: 'us-east-1-fake',
retryable: true,
time: 2020-08-12T10:18:08.321Z },
time: 2020-08-12T10:18:08.321Z }
Result:
null
Finished execution.
I then did more research and came across this thread about inaccessible-dynamodb-host-when-running-amplify-mock which I followed and tried implementing to but to no avail. Any help on this would be very much appreciated.
PS: It is worth mentioning that I was able to successfully query for this data through the Appsync console, which led me to strongly believe the problem lies in the function itself.
After doing more research and asking around, I finally made sense of the answer that was provided to me on github that
When running mock on a function which has access to a dynamodb
table generated by API. It will populate the env with fake values. If
you would like to mock your lambda function against your deployed
dynamodb table you can edit the values in the sdk client so it can
make the call accurately.
In summary, if you are running things locally, then you wouldn't have access to your backend variables which you might try mocking. I hope this helps someone. Thanks!

Unsupported content type with GraphIql apollo engine

I'm running apollo-server-express, and all works fine. I have 2 endpoints - 1 for graphiql (/graphql) and one for non-interactive (/client) queries (I know - they were called that before I started with apollo).
app.use('/client', bodyParser.json() ,
(req, res,next) => {
const context = { pool , apiKey:req.query.key , bidules };
if (server.isAuthorized(context.apiKey)) {
return graphqlExpress({
schema: schema,
context: context,
tracing: true,
cacheControl: {
defaultMaxAge: 30,
}
}) (req,res,next);
}
else {
res.setHeader('Content-Type', 'application/json');
res.status(403)
.send (JSON.stringify({
errors:[ {message: "api key is unauthorized"} ]
}));
}
}
);
// endpoint for browser graphIQL
app.use('/graphql', graphiqlExpress({
endpointURL: '/client'
}));
app.use("/schema", (req, res) => {
res.set("Content-Type", "text/plain");
res.send(printSchema(schema));
});
But, when I introduce apollo engine
engine.listen({
port: port,
expressApp: fidserver.app,
graphqlPaths: ['/graphql', '/client']
});
everything still works fine - except when I refresh graphiql on the browser with the query as parameters on the browser url.
Then I get this error
{"errors":[{"message":"Unsupported Content-Type from origin: text/html"}]}
Doing the same thing without apollo engine running does not cause an error. If run the query again, or refresh the browser without the query and variable parameters everything works just fine with or without Apollo Engine enabled.
When the error happens I can see from my server log that it's trying to return a react web page containing some javascript for decoding parameters from somewhere but I can't track down from where - it doesn't get as far as hitting any of my code.
This was solved by the guys at Apollo. Here's the answer - I shouldn't have had my graphIQL end point mentioned in the engine.listen options.
Engine should only be placed between the client and the GraphQL server endpoint. Try a config like this:
engine.listen({
port: port,
expressApp: fidserver.app,
graphqlPaths: ['/client'] // removed "graphql"
});

Get IP address using uWebSockets

Please, how can I get sender IP address using uWebSockets?
const wss = new uws.Server({
server: server,
perMessageDeflate: false
});
wss.on(`connection`, ws => {
ws.remoteAddress = ws.upgradeReq.connection.remoteAddress;
console.log(`user connected: `, ws.remoteAddress);
});
user connected is undefined
Please try this:
wss.on(`connection`, ws => {
ws.remoteAddress = ws._socket.remoteAddress;
console.log(`user connected: `, ws.remoteAddress);
});
You can also log ws._socket to know what it is.
ws._socket.remoteAddress should work , but if you ws server is behind a load balancer, you can get it via :
ws.upgradeReq.headers["x-forwarded-for"]

failed to load source: unsupported URL when trying a post request

I'm trying to use a simple post request on a route on top of a mongo DB.
my js file (I combined the router with the app) looks like:
var express = require('express');
var app = express();
var router = express.Router();
app.use(express.static('public'));
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
//Close connection
//db.close();
}});
router.post('/', function(req, res){
res.send('Got a POST request');
});
app.listen(27017,function(){
console.log("Server started successfully at Port 27017!");
});
on my html file I simple have a section like this (yes, my post request doesn't do much for now):
$.ajax({
method: "POST",
url: "localhost:27017/test/",
});
I can't seem to get it to work, my console keeps throwing: "[Error] Failed to load resource: unsupported URL (localhost:27017/test/, line 0)"
at me, and when I try to browse directly to the url via my browser I'm getting a "Cannot GET /test/" message.
What am I doing wrong?
Sharing what worked for me in the end:
1. Changed the app to listen to 3000 (or any other port that my DB server wasn't listening to). Thanks TomG.
2.changed router.post to app.post (you can use expressing routing but I had a mistake there).

Resources