Using SocketIo Manager with a default URL - socket.io

My goal is to add a token in the socketio reconnection from the client (works fine on the first connection, but the query is null on the reconnection, if the server restarted while the client stayed on).
The documentation indicates I need to use the Manager to customize the reconnection behavior (and add a query parameter).
However, I'm getting trouble finding how to use this Manager: I can't find a way to connect to the server.
What I was using without Manager (works fine):
this.socket = io({
query: {
token: 'abc',
}
});
Version with the Manager:
const manager = new Manager(window.location, {
hostname: "localhost",
path: "/socket.io",
port: "8080",
query: {
auth: "123"
}
});
So I tried many approaches (nothing, '', 'http://localhost:8080', 'http://localhost:8080/socket.io', adding those lines to the options:
hostname: "localhost",
path: "/socket.io",
port: "8080" in the options,
But I couldn't connect.
The documentation indicates the default URL is:
url (String) (defaults to window.location)
For some reasons, using window.location as URL refreshes the page infinitely, no matter if I enter it as URL in the io() creator or in the new Manager.
I am using socket.io-client 3.0.3.
Could someone explain me what I'm doing wrong ?
Thanks

Updating to 3.0.4 solved the initial problem, which was to be able to send the token in the initial query.
I also found this code in the doc, which solves the problem:
this.socket.on('reconnect_attempt', () => {
socket.io.opts.query = {
token: 'fgh'
}
});
However, it doesn't solve the problem of the Manager that just doesn't work. I feel like it should be removed from the doc. I illustrated the problem in this repo:
https://github.com/Yvanovitch/socket.io/blob/master/examples/chat/public/main.js

Related

"Error: Unknown dialect undefined" when deploying Strapi 4.0 app to Heroku

I created a Strapi app using the latest version, the new 4.0 and I wanted to deploy it to Heroku. I did follow the Strapi documentation in order to do so, like explained in this page. Now I'm getting an error that I don't understand, I guess it has something to do with postgres. This is the error
2021-12-18T15:26:26.658380+00:00 app[web.1]: [2021-12-18 15:26:26.656] debug: ⛔️ Server wasn't able to start properly.
2021-12-18T15:26:26.659122+00:00 app[web.1]: [2021-12-18 15:26:26.658] error: Unknow dialect undefined
2021-12-18T15:26:26.659123+00:00 app[web.1]: Error: Unknow dialect undefined
2021-12-18T15:26:26.659123+00:00 app[web.1]: at getDialectClass (/app/node_modules/#strapi/database/lib/dialects/index.js:12:13)
2021-12-18T15:26:26.659123+00:00 app[web.1]: at getDialect (/app/node_modules/#strapi/database/lib/dialects/index.js:19:23)
2021-12-18T15:26:26.659124+00:00 app[web.1]: at new Database (/app/node_modules/#strapi/database/lib/index.js:38:20)
2021-12-18T15:26:26.659124+00:00 app[web.1]: at Function.Database.init (/app/node_modules/#strapi/database/lib/index.js:84:33)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at Strapi.bootstrap (/app/node_modules/#strapi/strapi/lib/Strapi.js:347:30)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at Strapi.load (/app/node_modules/#strapi/strapi/lib/Strapi.js:410:16)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at async Strapi.start (/app/node_modules/#strapi/strapi/lib/Strapi.js:161:9)
Apart from doing what is explained in the docs I linked, I just added a few collections using the UI in development mode. How can I fix this error and deploy to Heroku this new 4.0 version of Strapi?
I had a similar issue when I was connecting pg locally and then realised my connection config was incorrect. When I replaced it with v4 template it worked.
path: config/database.js
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "bank"),
username: env("DATABASE_USERNAME", "postgres"),
password: env("DATABASE_PASSWORD", "0000"),
schema: env("DATABASE_SCHEMA", "public"),
},
}
});
And for Heorku as the article suggested:
path: config/env/production/database.js:
const parse = require('pg-connection-string').parse;
const config = parse(process.env.DATABASE_URL);
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false
},
},
debug: false,
},
});
PS: make sure you add pg-connection-string to your dependencies before pushing to heroku
getDialectClass - from the error log
const getDialectClass = client => {
switch (client) {
case 'postgres':
return require('./postgresql');
case 'mysql':
return require('./mysql');
case 'sqlite':
return require('./sqlite');
default:
throw new Error(`Unknow dialect ${client}`);
}
};
where the client is - db.config.connection
So if you have been following previous solutions - which talked about a connections object etc ( like this )
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: config.host,
port: config.port,
database: config.database,
username: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
options: {
ssl: true,
},
},
},
});
db.config.connection would return undefined. & so it would fail
Configuring the DB with - https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/databases.html#configuration-structure
Works fine
If you are using typescript in Strapi, we may encounter this issue too as there is a issue affecting Strapi typescript capabilities.
I can resolve the problem when I downgraded Strapi to 4.3.2 from 4.3.8
You can check this method using heroku/cli from strapi docs here, but it's the same thing, i'm using version 4.0.2, this methods works on older versions V3, i think the docs needs update, most of it is deprecated, for example "fetching only data (example: posts/project etc..) related to the authenticated user who created it", most of resources related to this topic in docs and forum are deprecated solutions that don't work in V4.
For the deployment, i have the same issue, i tried a lot of solutions but it didn't work for me to, but i managed to get the server running like this:
but i got this problem when i visit the "/admin" page:
Strapi is really interesting, let's hope they update the docs soon and someone respond with a solution here.
I fixed this issue by using database url directly. Not sure why the old way does not work in Strapi v4.
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
},
}
});
In case someone meets the same problem as me.
In my situation, I am using vim in windows as my text editor. After editing the "config/database.js" file. It left a "database.js~" file in that directory. Then, this filename causes the same problems: "Error: Unknown dialect undefined".
I guess it's a bug in strapi. After removing that file, everything works!
So, the solutions for me. I add this line to my vim config file:
set backupdir=~/.vimbackup
Then create a directory named '.vimbackup' in "C:/User/[me]/" .
Strapi has once again changed the database configuration structure and even their deployment docs use the old and incorrect example.
Here is the most up to date example: Strapi Database Configuration
In strapi v4, you need to use like:
module.exports = ({ env }) => ({
connection: {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "db-name"),
user: env("DATABASE_USERNAME", "postgres"),
password: env("DATABASE_PASSWORD", "password"),
schema: env("DATABASE_SCHEMA", "public"),
},
}
});
it's look like there is a problem in the new strapi version , when i try to create project with typescript support i faced same error , i don't know if you are using typescript in your project but these two solutions solved my problem;
solution (1) :- create compile config ts files with tsc $ tsc .\config\database.ts .\config\server.ts ./ .\config\admin.ts
solution (2) :- downgrade your strapi to 4.3.2 version in the package.json file.
solution (3) :- don't use #latest when creating strapi app instate use 4.3.2 npx create-strapi-app#4.3.2 test-strapi-verion-with-ts --ts
you can use one of theme

typescript security hotspot in environement.ts file, SonarQube

I have an environement.ts file like this:
export const environment = {
production: false,
HOST: 'http://192.192.192.1:8081/Services/api',
API_ENDPOINT: '',
API_ENDPOINT_LOGIN: '',
ASSETS_PATH: 'assets/images/',
ENV:'dev'
};
environment.API_ENDPOINT = environment.HOST + '/web/';
environment.API_ENDPOINT_LOGIN = environment.HOST + '/login/userlogin/';
SonarQube is givng Security Hotspot on this line: HOST: 'http://192.192.192.1:8081/Services/api', I am not sure what the problem/solution is. Need some help.
Thanks
Without seeing the output of SonarQube, I can't say for sure but I'm fairly confident that the issue is that you're using an http endpoint and not an https endpoint meaning that the connection would not be secured (encrypted with TLS)

Suddenly, Heroku credentials to a PostgreSQL server gives FATAL password for user error

Without changing anything in my settings, I can't connect to my PostgreSQL database hosted on Heroku. I can't access it in my application, and is given error
OperationalError: (psycopg2.OperationalError) FATAL: password authentication failed for user "<heroku user>" FATAL: no pg_hba.conf entry for host "<address>", user "<user>", database "<database>", SSL off
It says SSL off, but this is enabled as I have confirmed in PgAdmin. When attempting to access the database through PgAdmin 4 I get the same problem, saying that there is a fatal password authentication for user '' error.
I have checked the credentials for the database on Heroku, but nothing has changed. Am I doing something wrong? Do I have to change something in pg_hba.conf?
Edit: I can see in the notifications on Heroku that the database was updated right around the time the database stopped working for me. I am not sure if I triggered the update, however.
Here's the notification center:
In general, it isn't a good idea to hard-code credentials when connecting to Heroku Postgres:
Do not copy and paste database credentials to a separate environment or into your application’s code. The database URL is managed by Heroku and will change under some circumstances such as:
User-initiated database credential rotations using heroku pg:credentials:rotate.
Catastrophic hardware failures that require Heroku Postgres staff to recover your database on new hardware.
Security issues or threats that require Heroku Postgres staff to rotate database credentials.
Automated failover events on HA-enabled plans.
It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. For example, you may follow 12Factor application configuration principles by using the Heroku CLI and invoke your process like so:
DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
This way, you ensure your process or application always has correct database credentials.
Based on the messages in your screenshot, I suspect you were affected by the second bullet. Whatever the cause, one of those messages explicitly says
Once it has completed, your database URL will have changed
I had the same issue. Thx to #Chris I solved it this way.
This file is in config/database.js (Strapi 3.1.3)
var parseDbUrl = require("parse-database-url");
if (process.env.NODE_ENV === 'production') {
module.exports = ({ env }) => {
var dbConfig = parseDbUrl(env('DATABASE_URL', ''));
return {
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: dbConfig.driver,
host: dbConfig.host,
port: dbConfig.port,
database: dbConfig.database,
username: dbConfig.user,
password: dbConfig.password,
},
options: {
ssl: false,
},
},
},
}
};
} else {
// to use the default local provider you can return an empty configuration
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'sqlite',
filename: env('DATABASE_FILENAME', '.tmp/data.db'),
},
options: {
useNullAsDefault: true,
},
},
},
});
}

Auto Reload of gateway for schema changes in federated service apollo GraphQL

In Apollo Federation, I am facing this problem:
The gateway needs to be restarted every time we make a change in the schema of any federated service in service list.
I understand that every time a gateway starts and it collects all the schema and aggregates the data graph. But is there a way this can be handled automatically without restarting the Gateway as it will down all other unaffected GraphQL Federated services also
Apollo GraphQL , #apollo/gateway
There is an experimental poll interval you can use:
const gateway = new ApolloGateway({
serviceList: [
{ name: "products", url: "http://localhost:4002" },
{ name: "inventory", url: "http://localhost:4001" },
{ name: "accounts", url: "http://localhost:4000" }
],
debug: true,
experimental_pollInterval:3000
})
the code above will pull every 3 seconds
I don't know other ways to automatically reload the gateway other than polling.
I made a reusable docker image and i will keep updating it if new ways to reload the service emerge. For now you can use the POLL_INTERVAL env var to periodically check for changes.
Here is an example using docker-compose:
version: '3'
services:
a:
build: ./a # one service implementing federation
b:
build: ./b
gateway:
image: xmorse/apollo-federation-gateway
ports:
- 8000:80
environment:
CACHE_MAX_AGE: '5' # seconds
POLL_INTERVAL: '30' # seconds
URL_0: "http://a"
URL_1: "http://b"
You can use express to refresh your gateway's schema. ApolloGateway has a load() function that go out to fetch the schemas from implementing services. This HTTP call could potentially be part of a deployment process if something automatic is needed. I wouldn't go with polling or something too automatic. Once the implementing services are deployed, the schema is not going to change until it's updated and deployed again.
import { ApolloGateway } from '#apollo/gateway';
import { ApolloServer } from 'apollo-server-express';
import express from 'express';
const gateway = new ApolloGateway({ ...config });
const server = new ApolloServer({ gateway, subscriptions: false });
const app = express();
app.post('/refreshGateway', (request, response) => {
gateway.load();
response.sendStatus(200);
});
server.applyMiddleware({ app, path: '/' });
app.listen();
Update: The load() function now checks for the phase === 'initialized' before reloading the schema. A work around might be to use gateway.loadDynamic(false) or possibly change gateway.state.phase = 'initialized';. I'd recommend loadDyamic() because change state might cause issues down the road. I have not tested either of those solutions since I'm not working with Apollo Federation at the time of this update.

Cannot fire Bigcommerce webhooks

so far I've managed to create two webhooks by using their official gem (https://github.com/bigcommerce/bigcommerce-api-ruby) with the following events:
store/order/statusUpdated
store/app/uninstalled
The destination URL is a localhost tunnel managed by ngrok (the https) version.
status_update_hook = Bigcommerce::Webhook.create(connection: connection, headers: { is_active: true }, scope: 'store/order/statusUpdated', destination: 'https://myapp.ngrok.io/bigcommerce/notifications')
uninstall_hook = Bigcommerce::Webhook.create(connection: connection, headers: { is_active: true }, scope: 'store/app/uninstalled', destination: 'https://myapp.ngrok.io/bigcommerce/notifications')
The webhooks seems to be active and correctly created as I can retrieve and list them.
Bigcommerce::Webhook.all(connection:connection)
I manually created an order in my store dashboard but no matter to which state or how many states I change it, no notification is fired. Am I missing something?
The exception that I'm seeing in the logs is:
ExceptionMessage: true is not a valid header value
The "is-active" flag should be sent as part of the request body--your headers, if you choose to include them, would be an arbitrary key value pair that you can check at runtime to verify the hook's origin.
Here's an example request body:
{
"scope": "store/order/*",
"headers": {
"X-Custom-Auth-Header": "{secret_auth_password}"
},
"destination": "https://app.example.com/orders",
"is_active": true
}
Hope this helps!

Resources