nestjs / sequelize Goto Github PK
View Code? Open in Web Editor NEWSequelize module for Nest framework (node.js) π
Home Page: https://nestjs.com
License: MIT License
Sequelize module for Nest framework (node.js) π
Home Page: https://nestjs.com
License: MIT License
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
SequelizeModule.forRoot({
dialect: 'mysql',
host: 'xx',
port: 3306,
username: 'xx',
password: 'xx',
database: 'xx',
autoLoadModels: true,
synchronize: true
}),
Can run normally
await
"@nestjs/common": "^6.3.0",
"@nestjs/core": "^6.3.0",
"@nestjs/graphql": "^6.2.4",
"@nestjs/passport": "^6.0.0",
"@nestjs/platform-express": "^6.3.1",
"@nestjs/sequelize": "^0.1.0"
await NestFactory.create(ApplicationModule, {
cors: true,
logger: false
})
**Paused at this position**
For Tooling issues:
- Node version: v10.20.0
- Platform: Linux
Others:
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Not explicitely providing the synchronize: false
option to the module calls the sequelize.sync()
method which can alter a database in unexpected ways.
Not explicitely providing the synchronize
option shouldn't call the sequelize.sync()
method.
I believe having the synchronize
option enabled by default can be quite unforgiving if forgotten or omitted as this isn't a sequelize default behaviour (you have to explicitely call sequelize.sync()
) and would be safer for projects relying on another database syncing mechanism (migrations, etc.).
Also the documentation doesn't appear really clear to me (keeping both original sync
option and the new synchronize
option).
Thanks for the consideration!
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
uuid
, @types/uuid
)docker-compose.yml
postgres 15.3
package.json
uuid 9.0.1
@commitlint/cli 19.3.0
@commitlint/config-angular 19.3.0
@nestjs/common 10.3.10
@nestjs/core 10.3.10
@nestjs/platform-express 10.3.10
@nestjs/testing 10.3.10
@types/jest 29.5.12
@types/node 20.14.11
@types/supertest 6.0.2
@types/uuid 9.0.8
@typescript-eslint/eslint-plugin 7.16.1
@typescript-eslint/parser 7.16.1
eslint 8.57.0
eslint-config-prettier 9.1.0
eslint-plugin-import 2.29.1
husky 9.0.11
jest 29.7.0
lint-staged 15.2.7
mysql 2.18.1
pg 8.12.0
prettier 3.3.3
reflect-metadata 0.2.2
release-it 17.6.0
rxjs 7.8.1
sequelize 6.37.3
sequelize-typescript 2.1.6
supertest 7.0.0
ts-jest 29.2.2
typescript 5.5.3
@nestjs/common ^8.0.0 || ^9.0.0 || ^10.0.0
@nestjs/core ^8.0.0 || ^9.0.0 || ^10.0.0
reflect-metadata ^0.1.13 || ^0.2.0
rxjs ^7.2.0
sequelize ^6.3.5
sequelize-typescript ^2.0.0
@gperdomor there are a few minor breaking changes. You can find the migration guide & instructions on the 8.0.0
branch of the docs https://github.com/nestjs/docs.nestjs.com/tree/8.0.0
Originally posted by @kamilmysliwiec in nestjs/nest#6349 (comment)
This link is not available anymore where can I find those references?
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
My current setup that works fine to connect to the the Azure SQL Server DB using a service account:
SequelizeModule.forRoot({ dialect: 'mssql', host: envConfig.DB_HOST, port: envConfig.DB_PORT, username: envConfig.DB_USER, password: envConfig.DB_PASSWORD, database: envConfig.DB_NAME, models: [Model01, Model02], synchronize: true, dialectOptions: { options: { encrypt: true, enableArithAbort: true, connectionIsolationLevel: ISOLATION_LEVEL.READ_UNCOMMITTED, requestTimeout: 300000 } } })
I already have Azure AD integrating in my App that gives me accessToken
. From tedious
documentation I can see there is a way to specify authentication
setting like this:
authentication: { type: 'azure-active-directory-access-token', options: { token: 'access-token-from-azure-ad-login' } }
Could you please point me to the documentation/configuration how can I initiate DB connection for each of the logged-in user by passing their accessToken
to the SequelizeModule configuration with Model definition I posted above.
Thanks,
Good afternoon
Is it possible that there is a bug when connecting to MSSQL
Can you check that the code from the documentation works exactly ?
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.
[ ] Regression
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Throw error because Sequelize is not part of Sequelize Module
Should resolved Sequelize models dependencies without trowing
https://github.com/heritiermwalila/nest-sequelize-error
Nest version: X.Y.Z
8.0.0
For Tooling issues:
- Node version: v12.22.7
- Platform: Mac
Others:
Re-opening this issue as the previous one got closed and locked: #1237
The problem is not that my nestjs/common is outdated locally, is that the code in the nestjs/sequelize in npm was not built against the new nest/common. Hence the type inference for the injectModel function is based on the previous version of common, and therefore does not have the added | undefined
required.
Looking at the code here: https://www.npmjs.com/package/@nestjs/sequelize?activeTab=code
sequelize.decorators.d.ts
is properly inferred against the last nestjs/commonN/a
N/A
N/A
9.0.0
9.3.12
16.14
My nestJs common is at 9.3.12
(latest version to date)
I want to remove tedious @AllowNull(false)
decorators, and I found a solution here.
But Table is not created with omitNull option.
const models = [DefaultAccount, Account];
account.module.ts
@Module({
imports: [
SequelizeModule.forFeature(models, { omitNull: true }),
],
controllers,
providers: [
],
})
export class AccountModule { }
Table should be created, and all fields should be NOT NULL.
[System Information]
OS Version : macOS Catalina
NodeJS Version : v12.16.1
NPM Version : 6.14.8
[Nest CLI]
Nest CLI Version : 7.4.1
[Nest Platform Information]
platform-express version : 7.4.2
sequelize version : 0.1.1
passport version : 7.1.0
swagger version : 4.6.0
common version : 7.4.2
config version : 0.5.0
core version : 7.4.2
cqrs version : 7.0.1
jwt version : 7.1.0
Others:
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
When I try to use BulkCreate with the parameters ignoreDuplicates: false, updateOnDuplicate: [...] to make the inserts accuse this error:
DatabaseError [SequelizeDatabaseError]: syntax error at or near ")"
at Query.formatError (C:\Dev\Node\api-agruppa-suite\node_modules\sequelize\lib\dialects\postgres\query.js:366:16)
at C:\Dev\Node\api-agruppa-suite\node_modules\sequelize\lib\dialects\postgres\query.js:72:18
at tryCatcher (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\promise.js:547:31)
at Promise._settlePromise (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\promise.js:604:18)
at Promise._settlePromise0 (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\promise.js:649:10)
at Promise._settlePromises (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\promise.js:725:18)
at _drainQueueStep (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\async.js:93:12)
at _drainQueue (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\async.js:86:9)
at Async._drainQueues (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\async.js:102:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Dev\Node\api-agruppa-suite\node_modules\bluebird\js\release\async.js:15:14)
at processImmediate (internal/timers.js:439:21) {
name: 'SequelizeDatabaseError',
parent: error: syntax error at or near ")"
at Parser.parseErrorMessage (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:278:15)
at Parser.handlePacket (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket. (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\index.js:8:42)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
length: 93,
name: 'error',
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '56140',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1127',
routine: 'scanner_yyerror',
original: error: syntax error at or near ")"
at Parser.parseErrorMessage (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:278:15)
at Parser.handlePacket (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket. (C:\Dev\Node\api-agruppa-suite\node_modules\pg-protocol\dist\index.js:8:42)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
length: 93,
name: 'error',
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '56140',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1127',
routine: 'scanner_yyerror',
That make insert making the necessary updates in the records respecting my unique key composed.
DB: Postgress
My table
@table({
tableName: 'tb_categorias_omie',
schema: 'public',
timestamps: false,
paranoid: true,
})
export class Categoria extends Model {
@column({
type: DataType.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
})
public id: number;
@foreignkey(() => Empresa)
@column({
allowNull: false,
unique: 'compositeIndex',
type: DataType.INTEGER,
})
public id_empresa: number;
@BelongsTo(() => Empresa)
empresa: Empresa;
@column({ allowNull: false, type: DataType.TEXT })
public descricao: string;
@column({ allowNull: false, type: DataType.TEXT })
public descricao_padrao: string;
@column({ allowNull: false, unique: 'compositeIndex', type: DataType.STRING })
public codigo: string;
@column({ allowNull: false, type: DataType.STRING })
public categoria_superior: string;
@column({ allowNull: false, type: DataType.STRING })
public categoria_inativa: string;
@column({ allowNull: false, type: DataType.STRING })
public categoria_despesa: string;
@column({ allowNull: false, type: DataType.TEXT })
public natureza: string;
}
BulkCreate code:
await Categoria.bulkCreate(categorias, {
returning: true,
validate: true,
ignoreDuplicates: false,
updateOnDuplicate: [
'categoria_superior',
'categoria_inativa',
'categoria_despesa',
'descricao',
'descricao_padrao',
'natureza',
],
});
My dependencies:
"dependencies": {
"@nestjs/common": "^7.0.0",
"@nestjs/config": "^0.5.0",
"@nestjs/core": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"@nestjs/platform-socket.io": "^7.3.2",
"@nestjs/schedule": "^0.4.0",
"@nestjs/sequelize": "^0.1.0",
"@nestjs/websockets": "^7.3.2",
"moment": "^2.27.0",
"pg": "^8.3.2",
"pg-hstore": "^2.3.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"sequelize": "^5.22.3",
"sequelize-typescript": "^1.1.0"
},
I do an integration with an accounting system, it has some categories that use the same code for all companies but that can suffer changes in the name, standard name and superior category according to the need of that company.
Nest version: 7.4.1
For Tooling issues:
- Node version: 12.13.1
- Platform: Windows
Others:
Vscode
When configuring Sequelize with use factory and a single database Sequelize will resuse the connection as expected
SequelizeModule.forRootAsync({
useFactory: () => ({
dialect: 'postgres',
dialectModule: pg,
host: DB_HOST,
port: Number(DB_PORT),
database: 'postgres',
username: DB_USERNAME,
password: DB_PASSWORD,
autoLoadModels: true,
synchronize: true,
}),
}),
Image showing that only a single connection to the DB is made as the api is used
However when using a SequelizeOptionsFactory
that is request scoped (intention to enable multi tennant db on a request header stratergy) a new connection is made per api request. This means that eventually the API could use up all the connections on the database and result in an error by overwhelming the connections on the database.
@Injectable({scope:Scope.REQUEST})
export class SequelizeConfigService implements SequelizeOptionsFactory{
// The intention is you can resolve the DB from the request header
// constructor(@Inject(REQUEST) private readonly request:RequestContext){}
createSequelizeOptions(): SequelizeModuleOptions {
//const firmUuid = this.request.firmGuid;
let database = 'postgres';
// if (firmUuid) {
// database = `sqmfirm_${firmUuid}`;
// }
return {
dialect: 'postgres',
host: DB_HOST,
port: Number(DB_PORT),
database: database,
username: DB_USERNAME,
password: DB_PASSWORD,
autoLoadModels: true,
synchronize: true,
};
}
}
SequelizeModule.forRootAsync({
imports: [DatabaseConfigModule],
useExisting: SequelizeConfigService,
}),
Image showing the connections climbing as the api is used
https://github.com/dchosking/multitennant-connection-pool
npm install
npm start
Open browser to http://localhost:3000/
then contiunuisly Refresh.
Use what ever DB management tool you perfer and observe the connections to the DB climb
(Optional step If you set max connections to an arbitarly low number you can see the database begin to decline connections )
Docker compose for a DB with low number of max connections
version: '3.4'
services:
db:
image: postgres:13.5
command: postgres -c 'max_connections=20'
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: password
ports:
- 5432:5432
Expected behavior is Sequelize caching each connection to the database and then reusing that connection for subsequent requests
^9.0.0
^9.0.5
v14.19.0
No response
We use 3 db connections in our nest project, this requires 12 environment variables. We want to pass Sequelize options as a connection string instead of host, port, username and password. Currently we're using parse-database-url
package to get around this limitation.
Allow passing url param as a connection string.
Passing url as a parameter would allow users to create a Sequelize module using a connection string instead of passing host, port, username and password.
One environment variable (url) instead of many (host, port, username, passowrd).
[ ] Regression
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
It's possible upgrade sequelize dependency to 6.1.0 version?
[ ] Regression
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
In current setting, you are using the sequelize-typescript package.
Can it be a options to change to native Sequelize. As Sequelize 5 has been supported on typescript. (https://sequelize.org/v5/manual/typescript.html)
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Nestjs starts silently even when connection fails
Be able to test connection in bootstrap process
Nestjs should throw errors when connection fails to avoid runtime errors when methods are called.
See https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-authenticate
i have followed all steps to integrate sequelize to my project from
https://docs.nestjs.com/techniques/database#sequelize-integration but on the app.module.ts file i get this error when i add the User model in the models array
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './user/user.model';
@module({
imports: [
SequelizeModule.forRoot({
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
models: [User], //ERROR HERE
}),
],
})
export class AppModule {}
The errors i get when i hover over
Type 'typeof User' is not assignable to type 'string | ModelCtor<Model<any, any>>'.
Type 'typeof User' is not assignable to type 'ModelCtor<Model<any, any>>'.
Type 'typeof User' is not assignable to type 'typeof Model'.
Construct signature return types 'User' and 'Model<T, T2>' are incompatible.
The types of '_attributes' are incompatible between these types.
Type 'User' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'User'.
this is the user.model.ts file
import { Column, Model, Table } from 'sequelize-typescript';
@table
export class User extends Model {
@column
firstName: string;
@column
lastName: string;
@column({ defaultValue: true })
isActive: boolean;
}
Please advice
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Actually there is no module to handle versioning of database models.
I would like to know if there future implementation for a module like https://github.com/ivmarcos/sequelize-version or if there is a way to implement it with @nestjs/sequelize module.
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Currently, SequelizeModuleOptions.synchronize
is being typed as a boolean, which makes it impossible to pass in an additional { force: true }
option.
ref:
Good afternoon
I am trying to connect to the mssql database through the sequence
I get an error when connecting
SequelizeHostNotFoundError: Failed to connect to
I am connecting, as indicated in the official documentation
import {Module} from "@nestjs/common";
import { SequelizeModule } from "@nestjs/sequelize";
import {AppController} from "./app.controller";
import {AppService} from "./app.service";
import {UsersModule} from "./users/users.module";
import {User} from "./users/users.model";
@Module({
controllers:[AppController],
providers: [AppService],
imports: [
SequelizeModule.forRoot({
dialect: 'mssql',
host: "SLAVA\\SQLEXPRESS01",
port: 1433,
username: "sa",
password: "test",
database: "AmaLoyal",
models: [User],
autoLoadModels: true,
logging: console.log,
}),
UsersModule,
]
})
export class AppModule {}
package.json
{
"name": "test",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/mongoose": "^8.0.0",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/sequelize": "^8.0.0",
"@nestjs/typeorm": "^8.0.1",
"mongoose": "^5.13.3",
"mssql": "^7.1.3",
"mysql2": "^2.2.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"sequelize": "^6.6.5",
"sequelize-typescript": "^2.1.0",
"tds": "^0.1.0",
"tedious": "^11.4.0",
"typeorm": "^0.2.34"
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/express": "^4.17.13",
"@types/jest": "^26.0.24",
"@types/node": "^16.0.0",
"@types/sequelize": "^4.28.10",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/parser": "^4.28.2",
"eslint": "^7.30.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "27.0.6",
"prettier": "^2.3.2",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
I want to note that the connection with this data passes through PHP. I also have access to several mssql servers and the connection does not work on more than one
Tell me what I'm doing wrong or maybe there is an example of the code for connecting
A preview version of sequelize 7 has been released, Official support for typescript requires no third-party packages and applies to transaction usage AsyncLocalStorage Did very friendly support . Can you provide the corresponding preview version
An alpha version is available supporting sequelize v7
https://sequelize.org/docs/v7/
A preview version of sequelize 7 has been released, Official support for typescript requires no third-party packages and applies to transaction usage AsyncLocalStorage Did very friendly support
Currently this package uses sequelize-typescript. Iβd like to see this upgraded to utilize sequelize v7
Swap integration to sequelize/core trading v7, which contains all the native typescript typings, etc
Possibly version this in a way so people utilizing sequelize typescript donβt have to upgrade until ready
Motivation to use this is just keep things current with latest version of sequelize
Hi,
I'm trying to add a new database connection on my Nest project, but I do not success to do it even following the documentation (https://docs.nestjs.com/techniques/database#multiple-databases-1)
All was working well with my first database connection.
The error I obtain is "Nest can't resolve dependencies of the AccountsService (?, heroku_AccountRepository). Please make sure that the argument herokuConnection at index [0] is available in the AccountsModule context."
Here is my connections :
[
SequelizeModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
dialect: 'postgres',
host: configService.get<string>('db.host'),
port: configService.get<number>('db.port'),
username: configService.get<string>('db.user'),
password: configService.get<string>('db.password'),
database: configService.get<string>('db.database'),
schema: configService.get<string>('db.schema'),
autoLoadModels: true,
synchronize: false,
}),
inject: [ConfigService],
}),
SequelizeModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
name: 'heroku',
dialect: 'postgres',
host: configService.get<string>('heroku.host'),
port: configService.get<number>('heroku.port'),
username: configService.get<string>('heroku.user'),
password: configService.get<string>('heroku.password'),
database: configService.get<string>('heroku.database'),
schema: configService.get<string>('heroku.schema'),
autoLoadModels: true,
synchronize: false,
}),
inject: [ConfigService],
})
]
Here is my module :
import { Module } from '@nestjs/common';
import { AccountsService } from './accounts.service';
import { Account } from './account.model';
import { SequelizeModule } from '@nestjs/sequelize';
@Module({
imports: [
SequelizeModule.forFeature([Account], 'heroku')
],
providers: [AccountsService],
exports: [AccountsService]
})
export class AccountsModule {}
Here is my service :
import { Injectable } from '@nestjs/common';
import { Account } from './account.model';
import { InjectModel } from '@nestjs/sequelize';
@Injectable()
export class AccountsService {
constructor(
@InjectModel(Account, 'heroku')
private model: typeof Account,
) {}
async find(sfid: string): Promise<Account> {
return this.model.findOne({
where: { sfid }
});
}
}
I saw that maybe I need to inject the connection on the service but I do not success to do it. Specially I do not understand what is the Sequelize type in the example.
Does exist some github repo with sequelize multiple datatase example ?
Thank you by advance for your help,
Ben.
When I follow instructions to add this library to a nest application i get the following error from npm
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/reflect-metadata
npm ERR! reflect-metadata@"^0.2.0" from the root project
npm ERR! peer reflect-metadata@"^0.1.12 || ^0.2.0" from @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR! @nestjs/common@"^10.0.0" from the root project
npm ERR! peer @nestjs/common@"^8.0.0 || ^9.0.0 || ^10.0.0" from @nestjs/[email protected]
npm ERR! node_modules/@nestjs/sequelize
npm ERR! @nestjs/sequelize@"*" from the root project
npm ERR! 5 more (@nestjs/core, @nestjs/microservices, ...)
npm ERR! 3 more (@nestjs/core, @nestjs/microservices, @nestjs/websockets)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer reflect-metadata@"^0.1.13" from @nestjs/[email protected]
npm ERR! node_modules/@nestjs/sequelize
npm ERR! @nestjs/sequelize@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
no code created
nest new sequelize-test
npm i --save @nestjs/sequelize sequelize-typescript sequelize
in new project dirShould install sequelize and dependencies without error
latest (10.0.0?)
10.3.2
v18.16.0
No response
export const databaseProviders: Provider[] = [
{
provide: DATABASE_1,
inject: [ConfigService],
name: 'db1',
useFactory: async (configService: ConfigService): Promise<Sequelize> => {
const sequelize = new Sequelize({
...
});
sequelize.addModels([
...
]);
await sequelize.sync();
return sequelize;
},
},
{
provide: DATABASE_2,
inject: [ConfigService],
name: 'db2',
useFactory: async (configService: ConfigService): Promise<Sequelize> => {
const sequelize = new Sequelize({
...
});
sequelize.addModels([
...
]);
return sequelize;
},
},
];
I have the setup above, databaseProviders injected in database module. I want to implement nestjs terminus, but i can't get connection objects to pass in sequelizeHealthIndicator
Is it possible to use a database URL or connection string to initialize Sequelize?
The docs show this, but if many of our environments we use a string provided through an environment variable:
imports: [
ConfigModule.forRoot(),
SequelizeModule.forRoot({
dialect: 'postgres',
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT, 10),
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PWD,
database: process.env.DATABASE_DB,
logging: process.env.DATABASE_ENABLE_LOGGING === 'true',
ssl: process.env.DATABASE_REQUIRE_SSL === 'true',
}),
],
controllers: [StatusController],
providers: [],
})```
linked to #990
i am using a sequelize option factories to dinamically create connections by Request parameters.
now i want these providers to become durable but i am facing an issue:
following the doc. online, the providers are indeed durable, in that they are not re-created at every similar request. but the issue is that previously created providers are not correctly retrieved ... so in fact only the last added provider by contextId is picked ... these looks to me like an ugly bug ...
are durable providers perhaps only intended to work with typeorm ?? is there any COMPLETE example out there for how this would look like ?
No response
durable providers should use the same sequelize options
10
10
16
No response
With typescript 5, Any @InjectModel
has the following error attached to it:
Unable to resolve signature of parameter decorator when called as an expression.
Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'.ts(1239)
"@nestjs/sequelize": "^9.0.0" > sequelize.decorators.d.ts still has the following:
export declare const InjectModel: (entity: Function, connection?: string) => (target: object, key: string | symbol, index?: number | undefined) => void;
I may need to be re-compiled using the latest nestjs/common and re-deploy to npm, to get this bugfix in: nestjs/nest#10970
N/a
N/A
No error
9.0.0
9.3.12
16.14
No response
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I used @nestjs/config
to get the env is development or production
And used the @nestjs/sequelize
to create the sequelize instance
It look like the document
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
@Module({
imports: [
SequelizeModule.forRoot({
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
autoLoadModels: true,
synchronize: true,
sync: { force: true },
}),
],
})
export class AppModule {}
I want to set the sync: { force: false }
when the environment is 'production'
and set sync: { force: true }
when the environment is 'development'
null
null
Nest version: ^7.0.0
For Tooling issues:
Others:
@nestjs/sequelize: ^0.1.0,
@nestjs/config": ^0.5.0,
[ ] Regression
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Using Sequelize models with class-transformer and ClassSerializerInterceptor crash the app with Maximum call stack size exceeded error.
Serialize models without error.
Nest version: 7.0.7
For Tooling issues:
- Node version: 12.16.1
- Platform: All
Others:
"@nestjs/sequelize": "^0.1.0",
"class-transformer": "^0.2.3",
"sequelize": "^5.21.5",
"sequelize-typescript": "^1.1.0"
[ ] Regression
[ ] Bug report
[ ] Feature request
[X] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
In order to execute a raw query I need access to the sequelize connection instance, since sequelize-typescript
doesn't offer a own query method (see here: sequelize/sequelize-typescript#281 (comment)).
How can I access the sequelize connection?
Could you also please add this information to the documentation for future reference?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.