Prisma documentation recommends to instantiate Prisma Client as below to avoid infamous Already 10 Prisma Clients are actively running issue;
import { PrismaClient } from '#prisma/client'
declare global {
// allow global `var` declarations
// eslint-disable-next-line no-var
var prisma: PrismaClient | undefined
}
export const prisma =
global.prisma ||
new PrismaClient({
log: ['query'],
})
if (process.env.NODE_ENV !== 'production') global.prisma = prisma
it runs OK in dev environment. What I need to ask, do I need this process.env.NODE_ENV !== 'production' check? Should I instantiate Prisma Client in production differently?
There's no harm in keeping the check. Your NODE_ENV will be production so the condition won't match and PrismaClient will not be assigned to global variable.
There isn't going to be hot reloading in the production environment so there's no need of reusing the same PrismaClient
Related
I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?
Trying to deploy Strapi on Heroku with Postgres as described here
https://strapi.io/documentation/v3.x/deployment/heroku.html
But I get this error
error: no pg_hba.conf entry for host "84.212.51.43", user "ssqqeaz***", database "d6gtu***", SSL off
I use Heroku Postgres add-on.
My database config:
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 27017),
database: env('DATABASE_NAME', 'strapi'),
username: env('DATABASE_USERNAME', ''),
password: env('DATABASE_PASSWORD', ''),
},
options: {
ssl: true
},
},
},
});
Why? Please help!
try to change ssl : true into ssl : false
The current configuration you've posted will not work with a Heroku Postgres database. The primary concern here is that you're reading components of your postgres database url out of manually set config vars. This is very much recommended against by Heroku because they may need to move the database to a new host in the case of disasters. DATABASE_URL is set by Heroku when you create a database on an app and it's the one config var you can rely on to stay up-to-date. Moving on...
You will need to parse the username, password, host, port and database name out of the DATABASE_URL config var and supply those to the attributes of the settings block. Based on the error you provided, I can tell you're not presently doing this because Heroku databse usernames all start with a 'u', so something is very wrong if you get the error user "ssqqeaz***". As a first step you might try hard coding these values in the settings block to make sure it works (make sure to rotate the credentials after you do it, or otherwise clean up your git history to prevent leaked creds). The pattern for a postgres connection url is something like this: postgres:// $USERNAME : $PASSWORD # $HOSTNAME : $PORT / $DATABASE_NAME.
Not sure if it will help moving your config around...
remove ssl from option Key
insert ssl after password inside of settings Key
eg.
ssl: env.bool('DATABASE_SSL', false),
also check your app config vars inside of Heroku and make sure you have the required postgres config vars setup and they match the heroku generated DATABASE_URL config var.
lastly check your ./config/server.js file and make sure your host is 0.0.0.0
eg.
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', '**********************************'),
},
},
});
Im on a mac(OS 10.14) using nodejs 14 and PostgresSQL 12.
I just installed Loopback4 and after following this tutorial Im not able to use any of the enpoints that use Models, ie that connect to Postgres, I constantly get a timeout.
It seems like its not even reaching the Postgres Server, but the error gives no information, just that the request times out.
There are no issues with the Postgres server since I can connect and request information with other nodejs applications to the same database.
I also tried to set this as the host host: '/var/run/postgresql/', same result.
I now tried the approach with a Docker container, setting the datasource files as follows:
import {inject, lifeCycleObserver, LifeCycleObserver} from '#loopback/core';
import {juggler} from '#loopback/repository';
const config = {
name: 'mydb',
connector: 'postgresql',
url: 'postgres://postgres:mysecretpassword#localhost:5434/test',
ssl: false,
};
// Observe application's life cycle to disconnect the datasource when
// application is stopped. This allows the application to be shut down
// gracefully. The `stop()` method is inherited from `juggler.DataSource`.
// Learn more at https://loopback.io/doc/en/lb4/Life-cycle.html
#lifeCycleObserver('datasource')
export class PostgresSqlDataSource extends juggler.DataSource
implements LifeCycleObserver {
static dataSourceName = 'PostgresSQL';
static readonly defaultConfig = config;
constructor(
#inject('datasources.config.PostgresSQL', {optional: true})
dsConfig: object = config,
) {
super(dsConfig);
}
}
With that same url I can log on my command line from my mac.
Is there a way to add logging and print any connection error? Other ways to debug it?
[UPDATE]
As of today Loopback4 Postgres connector does not work properly with Nodejs 14.
When starting the application, instead of running
npm start, you can set the debug string by running:
DEBUG=loopback:connector:postgresql npm start
If you want it to be more generic, you can use:
DEBUG=loopback:* npm start
I am having an issue connecting to a Postgres Heroku hobby dyno via a Glitch instance with Node. I've looked through posts with similar problems, but still cannot find a solution. I've tried setting an env var in Node PGSSLMODE="require"
and running the code below, but I always get the same error. Thank you
const pg = require('pg')
const { Client } = require('pg');
pg.defaults.ssl = true
const client = new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
UnhandledPromiseRejectionWarning: Error: self signed certificate at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
You can't set it as ssl:true because that means you are self assigning your own certificate. Since you are using Heroku own PostgreSQL database you have a SSL certificate already. All you need to do is determine if you want to require or disable it.
const client = new Client({
connectionString: process.env.DATABASE_URL,
sslmode: process.env.NODE_ENV === "production" ? "require" : "disable"
})
I want to point out that you don't have to add sslmode because it by defaults requires the ssl certificate but just to be safe add the sslmode.
i have installed mongodb (1.8.3) on two seperate servers and set them up to use "replica sets" as found here: http://www.mongodb.org/display/DOCS/Replica+Set+Tutorial
everything looks good so far: one server is recognized as primary, one as secondary (when i access them via commandline).
the problem is that i can't connect to the DB using node.js (0.4.10) and mongoose (2.1.0) like this:
var mongo = require('mongoose');
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname');
i always get the following error message:
TypeError: Cannot read property 'reconnectWait' of undefined
at new <anonymous> (/var/www/node/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connections/repl_set_servers.js:23:31)
at NativeConnection.doOpenSet (/var/www/node/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:80:18)
at NativeConnection.openSet (/var/www/node/node_modules/mongoose/lib/connection.js:252:8)
at Mongoose.connectSet (/var/www/node/node_modules/mongoose/lib/index.js:116:27)
...
searched around a bit and found a post somewhere saying that i also have to supply the name of the replica set - so i tried this instead:
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname', rs_name:"name_replicaset"});
what am i doing wrong here ...?!
ok, there was an error in the https://github.com/christkv/node-mongodb-native module. it's fixed now but not yet pushed to NPM. so for all you guys getting the same error, here is the fix:
https://github.com/christkv/node-mongodb-native/pull/340
after that, you can just say
var mongo = require('mongoose');
mongo.connectSet('mongodb://host:27018/testdb, host2:27017/testdb, host3:27019/testdb', function (err) {
if (err) {
console.log("could not connect to DB: " + err);
}
});
mongo.connection.on('open', function () {
console.log("mongodb connection open");
}