nestjs / typeorm Goto Github PK
View Code? Open in Web Editor NEWTypeORM module for Nest framework (node.js) ๐
Home Page: https://nestjs.com
License: MIT License
TypeORM module for Nest framework (node.js) ๐
Home Page: https://nestjs.com
License: MIT License
Hello !
I would like to open a new connection for my tests, on a different database than my "live" one. Same MySQL server, but different databases and users.
I'm using the ormconfig.json
for my app, but I would like to use the "js object" to define my configuration in my tests.
I have something like that in my *.e2e-spec.ts
file:
const ormConfig = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'test',
password: 'test',
database: 'test',
entities: [__dirname + '/../../src/**/*.entity{.ts,.js}'],
synchronize: true,
};
describe('My Tests', () => {
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot(ormConfig),
...
],
}).compile();
...
});
...
But the synchronize
seems to not work at all. When I run the tests, the database test
is never created, so the connection is failing.
Is the TestingModule has a different behavior than a regular Module for TypeORM ?
Is there a conflict with the ormconfig.json
file ?
Thank you !
I had installed the nestjs/typeorm, but it just not work or 'cannot be found'
Hi
I have two entities UserBasic and UserExtenstion
I had tried to add data to database but I'm not get error.
But the result is not my expect.
It finally add to UserBasic but UserExtenstion is nothing.
My relation is one UserBasic with many UserExtenstion.
My json look like
{
"Name": "Lux",
"EngName": "Protoss",
"ID_No": "J123456789",
"PassPort_No": null,
"Sex": null,
"Birthday": null,
"Com_Address": null,
"Com_Zip": null,
"Nom_Address": null,
"Nom_Zip": null,
"Nom_Tel": null,
"Mobile_Tel": null,
"Liaise_Name": null,
"Liaise_Relation": null,
"Liaise_Address": null,
"Liaise_Tel": null,
"E_Mail": null,
"Other_Email": null,
"Update_Date": null,
"Update_User": null,
"K_Delete": null,
"UserExtension": [
{
"Admit_Type": "EMP",
"Unit": "WorkCenter",
"Title": null,
"Date_Start": null,
"Date_Leave": null,
"Lead_Class": null,
"Office_Tel": null,
"Office_Ext": null,
"Update_Date": null,
"Update_User": null,
"K_Delete": null
},
{
"Admit_Type": "Teacher",
"Unit": "Office",
"Title": null,
"Date_Start": null,
"Date_Leave": null,
"Lead_Class": null,
"Office_Tel": null,
"Office_Ext": null,
"Update_Date": null,
"Update_User": null,
"K_Delete": null
}
]
}
My code look like
await this.userBasicRepository.create(user)
[ ] 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.
How to deal with transactions using NestJs dependency injection system?
Inject and utilize typeorm transactional commmands in NestJs;
The motivation is for test porpuses purposes. If i don't have the Typeorm transactional system in NestJs DI, i can't test it easily.
[ ] 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.
TypeOrmModule.forRoot('default')
is throwing as invalid code even though in the documentation states that it accepts the same arguments as createConnection()
does in Typeorm.
[{
"name": "default",
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "",
"password": "",
"database": "",
"entities": ["src/**/**.entity{.ts,.js}"],
"synchronize": false,
"migrationsTableName": "migrations",
"migrations": ["src/database/migrations/*{.ts,.js}"],
"cli": {
"migrationsDir": "src/database/migrations"
}
}, {
"name": "seed",
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "",
"password": "",
"database": "",
"entities": ["src/**/**.entity{.ts,.js}"],
"synchronize": false,
"migrationsTableName": "seeds",
"migrations": ["src/database/seeds/*{.ts,.js}"],
"cli": {
"migrationsDir": "src/database/seeds"
}
}]
It should pick the connection name from your ormconfig.js or json file like Typeorm does.
To stay up to date with Typeorm's codebase.
Nest version: 5.7.3
For Tooling issues:
- Node version: 10.5.0
- Platform: Mac
i am trying to inject repository in another like
but when i am trying to use method from injected repository i am getting error:
this.issueRepository.getProjects is not a function, but it is a function and i can call it inside service
Nest version: 5.4.0
Nest/typeorm version: 5.2.2
For Tooling issues:
- Node version: 9.9.0
- Platform: Windows
[ ] Regression
[X] 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.
TypeOrm has implemented caching behaviour. Typeorm documentation says you can use external cache such as Redis or some database instead of in-memory cache.
https://github.com/typeorm/typeorm/blob/master/docs/caching.md
When following the instructions Typeorm has provided there is an issue with setting the cache duration for Redis. The cache and the expiration seem to work correctly, but the Redis key has no expiry set.
I looked into TypeOrm repository for this issue and it seems they have implemented a fix for this.
typeorm/typeorm#2505
Fix seems to be included as a bug fix for Typeorm version 0.2.8. Nestjs @Module/typeorm 5.2.2 still uses version 0.2.7. Can we get a version update for this.
As a side note or feature request I was wondering if CacheModule from @nestjs/common could be used for typeorm cache.
My current implementation:
CacheModule.registerAsync({
inject: [ConfigurationService],
useFactory: async (configService: ConfigurationService) => ({
store: redisStore,
host: configService.get(Configuration.REDIS_HOST),
password: configService.get(Configuration.REDIS_PASSWORD),
port: configService.get(Configuration.REDIS_PORT),
duration: configService.get(Configuration.REDIS_CACHE_DURATION),
prefix: configService.get(Configuration.NAME).split(' ').join('')
}),
}),
TypeOrmModule.forRootAsync({
inject: [ConfigurationService],
useFactory: (configService: ConfigurationService): TypeOrmModuleOptions => ({
type: 'postgres',
host: configService.get(Configuration.DB_HOST),
port: parseInt(configService.get(Configuration.DB_PORT), 10),
username: configService.get(Configuration.DB_USER),
password: configService.get(Configuration.DB_PASSWORD),
database: configService.get(Configuration.DB_NAME),
retryDelay: 5000,
cache: {
type: 'redis',
options: {
host: configService.get(Configuration.REDIS_HOST),
port: configService.get(Configuration.REDIS_PORT),
password: configService.get(Configuration.REDIS_PASSWORD),
prefix: configService.get(Configuration.NAME).split(' ').join('')
},
duration: parseInt(configService.get(Configuration.REDIS_CACHE_DURATION), 10),
},
Typeorm should set expiration for cache duration and expire the data after the duration has been exceeded.
Using docker-compose. Add redis image to docker-compose and give the environment as environment variables to your app. Connect your app to redis using the environment variables you set up in app.module.ts.
Add cache true to the operation you want to see cached.
Run the operation and open redis-cli. Run command KEYS * to see all the keys that Redis has saved. Run TTL to see that the expiry is set to be -1.
Bug has already been fixed in new typeorm release. Bring the fix to nestjs module.
Nest version:
```
"@nestjs/common": "^5.4.0",
"@nestjs/core": "^5.4.0",
"@nestjs/swagger": "^2.5.1",
"@nestjs/typeorm": "^5.2.2",
```
For Tooling issues:
- Node version: v10.5.0
- Platform: Mac/Linux
- Redis: 4.x.x
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.
@Module({
providers: [
DatabaseService,
],
exports: [
DatabaseService,
],
imports: [
TypeOrmModule.forRootAsync({
useFactory: async (config: ConfigService) => {
const options = config.get('database.databases.email');
options.name = 'default';
options.entities = [__dirname + '/../app/entities/*.entity{.ts,.js}'];
return options;
},
inject: [ConfigService],
}),
TypeOrmModule.forRootAsync({
useFactory: async (config: ConfigService) => {
console.log('I AM IGNORED');
const options = config.get('database.databases.app');
options.name = 'app';
options.entities = [__dirname + '/../app/entities/*.entity{.ts,.js}'];
return options;
},
inject: [ConfigService],
}),
],
})
Nest only load's first import. The second one is ignored. The module should load all async modules.
BTW. Maybe it would be better if module can accept array of connection options?
Nest version: 5.3.7
For Tooling issues:
- Node version: v9.4.0
- Platform: Mac
Others:
This is not an issue but a question. How do I load graphql module (uses postgraphile) after the database is synced by typeorm so that postgraphile gets updated schema?
[ ] 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 can't understand how can I use migrations
with @nestjs/typeorm.
As developer, I want to have a doc explaining how to use @nestjs/typeorm migrations
.
Nest version: 5.0.0
For Tooling issues:
- Node version: 9.6.0
- Platform: Mac
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.
With the current implementation, there is no easy way to filter data through url query string.
Empowering Controllers the ability to resolve url querys & building an apropiate SelectQuery
using TypeORM QueryBuilder
.
@Controller('foo')
export class FooController {
@Get()
@Filterable()
filter(@ORMQuery() query //A SelectQuery built) {
// Call Provider here. In order to simplify the example I'll call Repository directly
return this.fooRepository.find(query);
}
}
Given a query string like:
foo/?name=foo&surname__contains=fake&fk__related_prop=2&page=2
It will return the following SelectQuery
:
const filterQuery = await connection
.getRepository(Foo)
.createQueryBuilder('foo')
.where('foo.name = foo')
.andWhere('surname like fake')
.innerJoinAndSelect(Foo, 'foo', 'foo.related_prop = 2')
.take(25)
.skip(25 * 2 - 1)
Update 02/27/2019
I found this library whose owner is @bashleigh that resolves pagination & limit problem (and filterParameters, right).
Could it be interesting to implement proposed feature in this library? Parsing query string and transform it like TypeORM findOptions
A very common use case is to be able to filter content for an endpoint using the url query format.
Nest version: @next
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.
I receive the following error:
/Users/app/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:9
if (entity.prototype instanceof typeorm_1.Repository ||
^
TypeError: Cannot read property 'prototype' of undefined
When I try including entities from other modules in TypeOrmModule.forFeature([...])
and
inject the repositories into a provider, I get the above error.
Nest version: 5.4.0
For Tooling issues:
- Node version: XX
- Platform:
Others:
Today I got really confused. I upgraded from 2.0.0 to 2.1.0. Since this is a minor change, it should be backwards-compatible [source], but my application broke:
Nest cannot export component / module that is not a part of the currently proccessed module (TypeOrmCoreModule).
After some debugging I realized 2.1.0 already has upgraded to Nest 5.x.x [proof], so that means it wont use the components
but the providers
property inside modules instead. Off course this will break my application, running Nest 4.x.x.
Seems like publishing the version 2.1.0 was a mistake (should have been 3.0.0 instead).
Mistakes happen, but I would have tracked down this error much quicker, if there were git tags
(so I can diff
different releases) and changelogs (so I can read it up, without looking through the source code).
I highly recommend to start those things.
You can fix this by downgrading:
npm i -s @nestjs/[email protected]
[ ] Regression
[X] 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 did npm install and npm start in your example 5 and have errors with database not exist. Maybe exist another way that just go to mysql console and create database there? In AppModule, where @InjectConnection exist in constructor, it does not work to create database.
constructor(@InjectConnection() private readonly connection: Connection) {
this.connection.query("CREATE DATABASE mydb");
}
[ ] 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.
Let's say that I have two mysql servers talking to each other and have a config like below and for some reasons both severs have the same table with name and attributes. So I create only one entity "Photo".
@Module({
imports: [
// ---
TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService, name: 'server_one' }),
TypeOrmModule.forFeature([Photo], 'server_one'),
TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService2, name: 'server_two' }),
TypeOrmModule.forFeature([Photo], 'server_two')
]
})
export class AppModule {}
And when I am trying to inject the Photo from "server_two" but I get only Photo from "server_one".
@Injectable()
export class TypeOrmService {
constructor(@InjectRepository(Photo) private readonly photo: Repository<Photo>) {}
}
Have a second parameter on @InjectRepository(Photo, 'server_name') to specify the server name.
@Injectable()
export class TypeOrmService {
constructor(
@InjectRepository(Photo, 'server_one') private readonly photoOne: Repository<Photo>,
@InjectRepository(Photo, 'server_two') private readonly photoTwo: Repository<Photo>
) {}
}
In typeorm-typedi-extensions, they have this functionality.
Optionally, you can specify a connection name in the decorator parameters:
@Service() export class PostRepository { @InjectRepository(Post, "custom-con-name") private repository: Repository<Post>; }
Nest version: 5.6.0
For Tooling issues:
- Node version: 8.12.0
- Platform: Windows
Others:
typeorm version: 0.2.0-alpha.13
ormconfig.json
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "test",
"database": "test",
"entities": ["src/**/**.entity.ts"],
"autoSchemaSync": true
}
app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { User } from './auth/user.entity';
@Module({
modules: [TypeOrmModule.forRoot([User]), AuthModule],
controllers: [AppController],
components: [],
})
export class ApplicationModule {}
I have one entity(Player) and path in config is 100% good, because typeorm is creating table in db AND when im using this.connection.getRepository("Player"
) it finds it too(no error), but when im trying to import it using TypeOrmModule.forFeature([Player])
i got this error.
@edit
i just find out that if in this.connection.getRepository
im using Player
class, not string it throws error too.
Code: https://github.com/Gecko222/game/tree/backend-refactor/src_server
PS. Stacktrace is showing wierd path:
Error
at new RepositoryNotFoundError (E:\repos\game\src\error\RepositoryNotFoundError.ts:12:22)
at EntityManager.getRepository (E:\repos\game\src\entity-manager\EntityManager.ts:769:19)
at Connection.getRepository (E:\repos\game\src\connection\Connection.ts:306:29)
at getRepository (E:\repos\game\node_modules\@nestjs\typeorm\typeorm.providers.js:8:22)
at Object.useFactory [as metatype] (E:\repos\game\node_modules\@nestjs\typeorm\typeorm.providers.js:11:37)
at Injector.<anonymous> (E:\repos\game\node_modules\@nestjs\core\injector\injector.js:84:59)
i dont have folder src.
Hi there,
Here is a sample spec:
import {Test} from '@nestjs/testing';
import {TestingModule} from '@nestjs/testing/testing-module';
import {getRepositoryToken} from '@nestjs/typeorm/typeorm.utils'; // Not publicly exposed
import { Repository } from "typeorm";
import {expect} from 'chai';
import * as sinon from "sinon";
import {Blob} from '../../entities/blob.entity';
import {BlobService} from './blob.service';
describe('BlobService', () => {
let sandbox: sinon.SinonSandbox;
let module: TestingModule;
let blobService: BlobService;
beforeEach(async () => {
sandbox = sinon.createSandbox();
module = await Test.createTestingModule({
components: [
{
provide: getRepositoryToken(Blob), // I prefer to use this method rather than hardcoding the 'BlobRepository' value
useValue: [sinon.createStubInstance(Repository)]
},
BlobService
]
}).compile();
blobService = module.get(BlobService);
});
afterEach(() => {
sandbox.restore();
});
it('should exist', () => {
expect(blobService).to.exist;
});
});
You can see that I want to inject a repository stub: thus, I need to know the injection token associated to this repository. I've found the getRepositoryToken
method but it is not publicly exposed.
I don't know if things are like this on purpose but I think this function should also be exposed from the barrel file.
[ ] 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.
@Entity()
export class User {
// ...
@VersionColumn({ type: 'smallint', unsigned: true })
version: number;
}
Results in:
CREATE TABLE `user` (
# ...
`version` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
I expected the following result:
CREATE TABLE `user` (
# ...
`version` smallint(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Here's a complete entity:
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, VersionColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id: string;
@Column({ type: 'varchar', length: 256 })
email: string;
@Column({ type: 'varchar', length: 64 })
password: string;
@CreateDateColumn({ type: 'timestamp' })
created_at: Date;
@UpdateDateColumn({ type: 'timestamp' })
updated_at: Date;
@VersionColumn({ type: 'smallint', unsigned: true })
version: number;
}
Consistency and saving disk space + improving performance.
Nest version: 5.1.0 (@nestjs/core), 5.3.0 (`nest --version`)
For Tooling issues:
- Node version: v8.11.2
- Platform: Mac
Others:
- Database: MySQL 5.5.5-10.2.6 MariaDB
- @nestjs/typeorm: 5.1.0
- typeorm: 0.2.7
Hi!. Nice work with the TypeOrmModule, I really enjoy it.
I'm wondering how can I clear the database (or even drop it) before each test.
Hey guys !
I'm using docker-compose for my mysql server, but I'm quite annoyed by having connection configuration in two different places:
docker-compose.yml
ormconfig.json
Would you have some ideas how to keep the connection in only one place ?
[ x ] Bug report
I'm defining my import as followed, for each entity that I want to use as a repository I define this in the forFeatures array.
imports: [
TypeOrmModule.forRoot(),
TypeOrmModule.forFeature([
Answer,
AnswerLog,
Group,
School,
SchoolYear,
Score,
ScoreCalculated,
Subject,
User,
ContentSuggestion,
Todo,
PlannedDay,
WallItem,
]),
],
When I look at the log I saw that the TypeOrmModule is creating multiple connections for each repository. My question why?
Cause I think this is causing when I sometimes get a DEAD_LOCK error.
I don't know if this is a bug or not?
[ ] 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.
I want use "typeorm": "^0.3.0-alpha.5";
But when i yarn.
typeorm will be install at node_modules/@nestjs/typeorm/node_modules/typeorm
it version alway keep "^0.2.3"
I have to remove it in package.json
"postinstall": "rimraf node_modules/@nestjs/typeorm/node_modules/typeorm",
just keep peerDependencies is good for everyone.
[ ] 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.
It is not clear how to properly inject a custom repository into their services, this is sadly not documented. People will look through old GitHub issues to find how others managed to solve their issues, this is far from ideal for various reasons.
A properly documented example so that people can figure out how to do it themselves.
First create your custom repository. I threw in some useless functions to show that it works.
@EntityRepository(Author)
export class AuthorRepository extends Repository<Author> {
test() {
console.log('testasfasdfasdf');
}
customSave(entity) {
return this.save(entity);
}
}
Then go to your feature module
@Module({
imports: [TypeOrmModule.forFeature([Author, AuthorRepository /* <--- put your custom repository here together with your entities */])],
providers: [AuthorService, AuthorResolver],
})
export class TestModule {
}
Now we go to our service
@Injectable()
export class AuthorService {
constructor(
@InjectRepository(AuthorRepository)
private readonly authorRepository: AuthorRepository, // <-- inject like this
) {
}
async create(author: AuthorInterface) {
this.authorRepository.test();
return await this.authorRepository.customSave(this.authorRepository.create(author));
}
}
Voila! You're done, you can now use your custom repository as if it was a default repository but with your own extra goodies!
Some proof that it works:
I use GraphQL so here's the other code:
@Resolver('Author')
export class AuthorResolver {
constructor(
private readonly authorService: AuthorService
) {
}
@Mutation('createAuthor')
async createAuthor(obj, args, context, info) {
return await this.authorService.create(args);
}
}
Execute the mutation
Result
Database
Console, to show that the console.log
function is called.
There's a risk people will use outdated answers like this one
People are more likely to look for other people's answers rather than finding their own.
Nest version: ^5.1.0
Nestjs/graphql: ^3.0.0
Nestjs/typeorm: ^5.1.0
For Tooling issues:
- Node version: 10.0.0
- Platform: Windows
Others:
This is my first GitHub issue. I'd like to have feedback in case there's something wrong with my it.
[ ] 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.
There is no way to pass connection options which is asynchronously created.
We should be able to pass asynchronously created connection options because it's natural that we encrypt sensitive information such as database credentials beforehand and decrypt it asynchronously after launching a server.
nestjs/typeorm module version: 5.0.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.
If you import a Class with @InjectRepository
and this class has a circular dependency, Typescript does not detect it inside of decorators. Then, the InjectRepository routine fails as it tries to import an undefined object that should be the TypeOrm class.
@InjectRepository
should help Typescript to detect this circular dependencies.
To do so, there is an issue related to the typeorm repo where they discuss this (and there is a note about this in the typeorm README):
ubiquits/quickstart#18
And also there is the original discussion in TypeScript repository here:
microsoft/TypeScript#4521
It seems the way around the issue is to pass a function rather than directly the class to the decorator.
So @InjectRepository
would be used such as @InjectRepository(() => TypeormEntity)
Nest version:5.7.4
Node: v11.9.0
Typescript: 3.3.3333
[ ] 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.
I am writing a Jest E2E test where a TypeOrmModule
was imported. If the name
was assigned a value other than 'default'
, the test script would be blocked at await app.close();
and the process would not exit until SIGTERM
was called.
The process exits automatically.
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import 'jest';
import { ConfigModule, ConfigService } from 'nestjs-config';
describe('tmp (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
app = (await Test.createTestingModule({
imports: [
ConfigModule.load(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
...config.get('pg'),
bigNumberStrings: true,
// change 'default' to any other string would hang the test
name: 'default',
supportBigNumbers: true,
}),
}),
],
}).compile()).createNestApplication();
await app.init();
});
it('tmp', (done) => {
done();
});
afterAll(async () => {
// this line would run
console.log('foo');
await app.close();
// this would not if 'default' was changed
console.log('bar');
});
});
package.json
version is 2.1.0
in master branch, but npm install @nestjs/typeorm@latest
installs 2.0.0 that published 4 months before. Is there some reason about not publishing latest version?
Hello,
It is really question not an issue but it may be good place to ask.
I am working on multi tenant application using nest. So far I have started by creating common base service and controllers which filter, check and assign tenant_id based on current context.
However having postgres schema per tenant would be better I think but i don't known how to implement it with nest and typeorm.
Any suggestions?
I have one module in my app, with the last update I should write this:
@Module({
imports: [
TypeOrmModule.forRoot({
/* Connection options goes here */,
entities: [/* Entities goes here */],
}),
TypeOrmModule.forFeature([/* Entities goes here */]),
]
})
Why? I've already pass my entities inside options. And now I importing the same module twice.
[ ] 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.
class AppModule:
imports: [
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService
}),
GrainModule.forRoot()
],
class TypeOrmConfigService:
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
...
}
}
class GrainModule:
static forRoot(): DynamicModule {
return {
module: GrainModule,
imports: [
TypeOrmModule.forFeature(
[...grainEntities, ...grainRepositories]
),
Error: Nest can't resolve dependencies of the RunRulesEntityRepository (?). Please make sure that the argument at index [0] is available in the
current context.
It's passed:
TypeOrmModule.forRoot(
new TypeOrmConfigService( ).createTypeOrmOptions()
),
It's throwed error:
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService
}),
How to use forRootAsync ?
Thanks!
Nest version: 5.3.7
For Tooling issues:
- Node version: 8.12.0
- Platform: Windows
Others:
With typeorm we can use custom repository to override default one to add extra methods.
For example:
@Component()
@EntityRepository(Jwt)
export class JwtRepository extends Repository<Jwt> {
}
After we juste have to inject it inside controller/model/service etc... like this:
constructor(
@OrmRepository('connectionName')
private readonly jwtRepository: jwtRepository,
But only InjectRepository decorator is available on nestjs, so if we try to inject repo into a service:
@Component()
export class MyService {
constructor(
@InjectRepository(Jwt)
private readonly jwtRepository: JwtRepository,
We got this error for any repo function:
Cannot read property 'findOne' of undefined
at JwtRepository.Repository.findOne
How it is possible to use custom repo?
[ ] 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 running local database with nestjs project while in development, I'm facing issue with nestjs project startup. While the database is starting up the nestjs/typeorm the retry logic runs through all the retry attempts and never succeeds even though database is already running. The error message which typeorm module provides displays the same error message for every retry-attempt until project aborts
When the database actually starts up it should connect to database.
TypeOrmModule.forRootAsync({
inject: [ConfigurationService],
useFactory: (configService: ConfigurationService): TypeOrmModuleOptions => ({
type: 'postgres',
host: configService.get(Configuration.DB_HOST), -- localhost
port: parseInt(configService.get(Configuration.DB_PORT), 10), --5432
username: configService.get(Configuration.DB_USER), --admin
password: configService.get(Configuration.DB_PASSWORD), --admin
database: configService.get(Configuration.DB_NAME), --testdb
retryDelay: 5000,
retryAttempts: 10,
entities: [
`${__dirname}/**/*.entity{.ts,.js}`
],
migrations: [
`${__dirname}/migrations/*{.ts,.js}`
],
migrationsRun: true,
synchronize: false,
logging: [
'query',
'error',
'warn',
'migration'
],
})
})
Retry logic should work as expected especially when starting local development environment with docker-compose.
"@nestjs/common": "^5.3.0",
"@nestjs/core": "^5.3.0",
"@nestjs/typeorm": "^5.2.0",
For Tooling issues:
- Node version: 10.5
- Platform: Mac
- Postgres 9.6
- Also tested with docker compose
Others:
With typeorm and typedi we can specify a connection name for a repository like this:
import { Service } from 'typedi';
import { OrmRepository } from 'typeorm-typedi-extensions';
import { ExampleRepository } from './example.repository';
@Service()
export class ExampleModel {
constructor(
@OrmRepository('myconnectionname')
private readonly repository: ExampleRepository) {
}
To manage multiple connections, we just have to use createConnections method instead of createConnection (as array of connection).
Why TypeOrmModule.forRoot method do not support Array?
I know, it will be implemented but if someone know when, it's welcome.
Is there a way to set connection name instead of default one?
I've configured HMR and it works fine.
With TypeORM there was some limitations that you have to import each entity manually without glob pattern.
So I did and it works until some of entities changed/edited. Then error thrown.
If I change Config
entity for example:
[Nest] 10524 - 2018-8-1 13:10:45 [ExceptionHandler] No repository for "Config" was found. Looks like this entity is not registered in current "default" connection?
RepositoryNotFoundError: No repository for "Config" was found. Looks like this entity is not registered in current "default" connection?
at new RepositoryNotFoundError (C:\Users\alex\Documents\_dev\apps_node\node_modules\typeorm\error\RepositoryNotFoundError.js:20:28)
at EntityManager.getRepository (C:\Users\alex\Documents\_dev\apps_node\node_modules\typeorm\entity-manager\EntityManager.js:580:19)
at Connection.getRepository (C:\Users\alex\Documents\_dev\apps_node\node_modules\typeorm\connection\Connection.js:358:29)
at getRepository (C:\Users\alex\Documents\_dev\apps_node\node_modules\@nestjs\typeorm\dist\typeorm.providers.js:13:26)
at Object.useFactory [as metatype] (C:\Users\alex\Documents\_dev\apps_node\node_modules\@nestjs\typeorm\dist\typeorm.providers.js:22:20)
at resolveConstructorParams (C:\Users\alex\Documents\_dev\apps_node\node_modules\@nestjs\core\injector\injector.js:67:55)
at Injector.resolveConstructorParams (C:\Users\alex\Documents\_dev\apps_node\node_modules\@nestjs\core\injector\injector.js:86:30)
at <anonymous>
1: std::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame> >::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame> >
2: v8::internal::CompilerDispatcherTracer::Estimate
3: v8::internal::CompilerDispatcher::RemoveJob
4: v8::internal::CompilerDispatcher::RemoveJob
5: v8::internal::CompilerDispatcher::RemoveJob
6: 0000037D4CA847A1
HMR output:
[HMR] Updated modules:
[HMR] - ./src/@core/config/config.entity.ts
[HMR] - ./src/@core/config/config.service.ts
[HMR] - ./src/@core/config/config.module.ts
[HMR] - ./src/app-one/db/entities.ts
[HMR] - ./src/app-one/db/db.module.ts
[HMR] - ./src/app-one/main.module.ts
[HMR] - ./src sync recursive ^\.\/.*\/main\.module$
[HMR] - ./src/app.module.ts
[HMR] - ./src/main.ts
[HMR] - ./src/app-one/common/common.module.ts
[HMR] - ./src/@core/config/config.resolver.ts
[HMR] Update applied.
Any ideas why it's happening ?
[x] Support request
Hi. How to inject a custom repository http://typeorm.io/#/custom-repository ? And second question this indicates that we shouldn't be creating services from custom repositories, especially if you want to use transactions. What do you think
? Best Regards
[ ] 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 am regularly facing issue with my AWS Connections, (I am still on AWS Free Tier).
When I run few queries using post man in a where short time, the number of connections goes up to 30 and then my server which is hosted on Zeit stops responding. I would like to ask for recommendation on how to come out of this problem.
I am using Typeorm 2.7 and @nestjs/typeorm ^5.0.0.
Also, I have custom repositories which doesn't extend Any Repository Class or Abstract Repository Class of Typeorm, so I have created my Repository Provider like this:
export const UserRepositoryProvider = {
provide: getRepositoryToken(User),
useFactory: (connection: Connection) => connection.getCustomRepository(UserRepository),
inject: [getConnectionToken()],
};
My Response should be normal and not be effected by Number of Request. Could I be doing something wrong, please give pointers
Nest version: X.Y.Z
For Tooling issues:
- Node version: 5.0.1
- Platform: Zeit (Node) with AWS PostgresSQL
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.
@InjectRepository()
and getRepositoryToken()
are generating misleading tokens for Custom Repositories for TypeORM. getRepositoryToken(UserRepository)
returns 'UserRepositoryRepository'
instead of the expected 'UserRepository'
It is expected that @InjectRepository(UserRepository)
and getRepositoryToken(UserRepository)
will reference 'UserRepository'
as an injection token.
This issue relates another issue in the wrong repo which describes the symptoms of this issue.
I'm getting an error if I try to import TypeOrmModule.forRoot() from a forRoot method in ApplicationModule.
app.module.ts
@Module({})
export class ApplicationModule {
static forRoot(): DynamicModule {
return {
module: ApplicationModule,
imports: [
TypeOrmModule.forRoot(),
PhotoModule
]
};
}
}
main.ts
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule.forRoot());
await app.listen(3001);
}
bootstrap();
Output with stacktrace:
[Nest] 8472 - 2018-5-9 23:01:01 [NestFactory] Starting Nest application...
[Nest] 8472 - 2018-5-9 23:01:01 [InstanceLoader] ApplicationModule dependencies initialized +115ms
[Nest] 8472 - 2018-5-9 23:01:01 [InstanceLoader] TypeOrmModule dependencies initialized +1ms
[Nest] 8472 - 2018-5-9 23:01:01 [ExceptionHandler] Cannot destructure property `relatedModules` of 'undefined' or 'null'.
TypeError: Cannot destructure property `relatedModules` of 'undefined' or 'null'.
at flatten (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:161:49)
at Array.map (<anonymous>)
at Injector.flatMap (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:169:54)
at Injector.lookupComponentInRelatedModules (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:136:42)
at Injector.lookupComponentInExports (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:127:44)
at scanInExports (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:123:42)
at Injector.lookupComponent (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:124:68)
at Injector.resolveComponentInstance (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:113:44)
at Injector.resolveSingleParam (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:102:27)
at Promise.all.args.map (C:\Users\Yannick\Desktop\nestjs typeorm\node_modules\@nestjs\core\injector\injector.js:80:45)
Nest cannot export component / module that is not a part of the currently proccessed module (TypeOrmCoreModule). Please verify whether each exported unit is available in this particular context.
Error: Nest cannot export component / module that is not a part of the currently proccessed module (TypeOrmCoreModule). Please verify whether each exported unit is available in this particular context.
at Module.validateExportedProvider (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/injector/module.js:224:19)
at Module.addCustomExportedComponent (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/injector/module.js:211:32)
at Module.addExportedComponent (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/injector/module.js:195:25)
at NestContainer.addExportedComponent (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/injector/container.js:113:16)
at DependenciesScanner.storeExportedComponent (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:135:24)
at exports.map.exportedComponent (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:86:47)
at Array.map (<anonymous>)
at DependenciesScanner.reflectExports (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:86:17)
at modules.forEach (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:39:18)
at Map.forEach (<anonymous>)
at DependenciesScanner.scanModulesForDependencies (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:35:17)
at DependenciesScanner.scan (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/scanner.js:17:14)
at NestFactoryStatic.<anonymous> (/Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/nest-factory.js:90:41)
at Generator.next (<anonymous>)
at /Users/theobouwman/dev/projects/webshop_top/node_modules/@nestjs/core/nest-factory.js:7:71
at new Promise (<anonymous>)
1: node::Abort() [/usr/local/bin/node]
2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]
3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/local/bin/node]
4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]
5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]
6: 0xb64332042fd
Can't find the issue and no one can help me on Stackoverflow either
[ ] 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.
I am getting this issue while trying to use the application context for my job queues. While NestFactory.createApplicationContext(AppModule)
is initialising the application module TypeOrm is creating connection with same default
name. How do I prevent it?
[Nest] 11985 - 2019-1-16 16:08:34 [TypeOrmModule] Unable to connect to the database. Retrying (1)... +31ms
AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
at new AlreadyHasActiveConnectionError (/var/www/sxapi/src/error/AlreadyHasActiveConnectionError.ts:8:9)
at ConnectionManager.create (/var/www/sxapi/src/connection/ConnectionManager.ts:57:23)
at Object.<anonymous> (/var/www/sxapi/src/index.ts:219:35)
at step (/var/www/sxapi/node_modules/typeorm/index.js:32:23)
at Object.next (/var/www/sxapi/node_modules/typeorm/index.js:13:53)
at /var/www/sxapi/node_modules/typeorm/index.js:7:71
at new Promise (<anonymous>)
at __awaiter (/var/www/sxapi/node_modules/typeorm/index.js:3:12)
at Object.createConnection (/var/www/sxapi/node_modules/typeorm/index.js:215:12)
at rxjs_1.defer (/var/www/sxapi/node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:137:29)
at Observable._subscribe (/var/www/sxapi/node_modules/rxjs/src/internal/observable/defer.ts:57:15)
at Observable._trySubscribe (/var/www/sxapi/node_modules/rxjs/src/internal/Observable.ts:224:19)
at Observable.subscribe (/var/www/sxapi/node_modules/rxjs/src/internal/Observable.ts:205:14)
at RetryWhenOperator.call (/var/www/sxapi/node_modules/rxjs/src/internal/operators/retryWhen.ts:39:19)
at Observable.subscribe (/var/www/sxapi/node_modules/rxjs/src/internal/Observable.ts:200:16)
at /var/www/sxapi/node_modules/rxjs/src/internal/Observable.ts:345:12
My Job Processor:
const VisitorCheckinNotificationProcessor = async (
job: Job,
done: DoneCallback,
) => {
// application context
const context = await NestFactory.createApplicationContext(AppModule);
let data: any = job.data;
console.log('[VISITOR_CHECKIN_NOTIFICATION_SENT]', data);
try {
await context.close();
} catch (e) {
console.log('[EXCEPTION WHILE TERMINATING APPLICATION CONTEXT]', e);
}
done(null, data);
};
app.module.ts
@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => ({
type: 'mysql',
host: config.mysqlHost,
port: config.mysqlPort,
username: config.mysqlUsername,
password: config.mysqlPassword,
database: config.databaseName,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: config.databaseSyncEnabled,
logging: config.databaseLoggingEnabled,
}),
inject: [ConfigService],
}),
CoreModule,
UserModule,
],
controllers: [AppController],
})
export class AppModule {}
Nest version: 5.4.0
For Tooling issues:
- Node version: 9.4
- Platform: Linux (Ubuntu 18.04)
[ ] 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.
The application freezes when it is starting.
Imagine that you have an entity: Photo
If you want to split into 2 repositories: PhotosReadRepository
and PhotosRepository
.
Both repositories need to inject the Typeorm repository:
@InjectRepository(Photo)
internalRepository: MongoRepository<Photo>,
And the PhotosRepository
have a dependecy to PhotosReadRepository
.
Usually I split my repositories with read and write+read.
Nest version: 5.0.1
[ ] 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.
@InjectRepository
fails with 'TypeError: Right-hand side of 'instanceof' is not an object'. when yarn test
https://github.com/osmanmesutozcan/nestjs-inject-repository-bug-repro
to run it:
yarn
yarn test
Nest version:
"@nestjs/common": "^5.4.0",
"@nestjs/core": "^5.4.0",
"@nestjs/graphql": "^5.5.7",
"@nestjs/typeorm": "^5.3.0",
For Tooling issues:
- Node version: 10.12.0
- Platform: Linux
Others:
I'm following this pattern of creating a ConfigService
that encapsulates all the configuration in the application. This works really well. However when working with TypeORMModule
, it seems that I need to provide the database credentials at module load time.
@Module({
imports: [TypeOrmModule.forRoot(getDbConfig())], // this line
providers: [...repoProviders],
exports: [...repoProviders],
})
export class DBModule {}
I would like to provide the getDbConfig()
values via dependency injecting ConfigService
. Can that be done?
[ ] 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.
When connecting to the MSql database I get: "Unable to connect to the database. Retrying (1)"
It turned out this was caused by an entity having @Column('description')
which is not allowed and should have beeld @Column()
took hours to figure this out since it looks like there is something wrong with the credentials.
A more verbose way of error e.g. Unable to connect: host unreachable, or password incorrect etc.
Also an option to show the credentials used would be very nice to debug connection issues. Currently I have no clue if the correct credentials are taken from my .env file.
The problem occurred as well when using Entities generated with https://github.com/Kononnable/typeorm-model-generator Apparently there is something wrong with an Entity but the console keeps telling me "Unable to connect to the database. Retrying (1)" instead of giving where something is wrong.
Create a DB connection with wrong credentials
Better debugging on connection errors.
Nest version: 5.0.0
For Tooling issues:
- Node version: 9.9.0
- Platform: Mac
Others:
Hi,
I really like the simplicity of this module but there is one thing I can not understand:
How do you dynamically configure the database connection when using TypeOrmModule.forRoot
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
...
}),
],
})
I have a similar ConfigService like the one in https://docs.nestjs.com/techniques/configuration in my application and want to use that for the configuration of the database connection but its embarrassing, I can't find a solution on how to use this configuration in combination with TypeOrmModule.
I know I could do the creation of the connection in a custom provider following https://docs.nestjs.com/recipes/sql-typeorm but isn't there a simpler way which is as convenient as this module?
Thanks for help and thank you for the hard work you all are putting into nestjs I really love it!
code is:
app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller'
@Module({
imports: [ TypeOrmModule.forRoot({
type: 'sqlite',
database: 'dev.db',
synchronize: true,
logging: false,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
}) ],
components: [ ],
controllers: [ AppController ]
})
export class ApplicationModule{}
entity.ts:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Demo {
@PrimaryGeneratedColumn()
id: number;
@Column({length: 100})
title: string;
@Column({length: 100})
name: string;
}
when i npm start,then throw this: (node:5723) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'join' of undefined
@nestjs/typeorm version is:2.0.0,typeorm version is: ^0.1.21
[ ] 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.
Route Model binding
As discussed here, it would be nice to have a decorator that will convert the id
(or any other unique key) passed in a route to a model instance.
For example:
@Controller('car')
export class CarController{
@Get(':id')
find(@Entity(Car) car: Car) {
return car;
}
@Get(':license_plate')
find(@Entity(Car, 'licensePlate') car: Car) {
return car;
}
}
Here, the car parameter in the method will be an instance of the Car
Entity. This is my current implementation of the @Entity
decorator
const Entity = createParamDecorator(async (data, req): Promise<PipeTransform<any>[]> => {
if (!Array.isArray(data)) {
data = [data, Object.keys(req.params)[0]];
}
const [type, param] = data;
const value = req.params[param];
const query = {};
query[param] = value;
const entity = await type.findOne(query);
if (!entity) {
throw new HttpException({error: 'Entity not found'}, 404);
}
return entity;
});
Unfortunately it works only for a few cases and it's kinda buggy but you get the idea.
I'm also thinking making it cleaner using reflection. I imagine something like this:
@Controller('car')
export class CarController{
@Get(':car')
find(car: Car) {
return car;
}
}
This is a little complicated. In this case the the parameter is resolved by the Router. In this case we need some binding mechanism(it should behave as the bind method of a DI container):
// router.provider.ts
router.bind(Entity, (class, value) => {
//`Entity` is the TypeORM Entity class used in the case of ActiveRecord pattern.
// When the router sees that it needs to pass and instance of Entity,
// It will run this callback in order to resolve it.
//`class` is the class got using reflection (`Car` in our above example)
//`value` is the value from the request where there route parameter has the same name as the `class`
let query = { id: value }; // or `let query = { licensePlate: value }`; depending on how you need to select
const entity = await class.findOne(query);
if (!entity) {
throw new HttpException({error: 'Entity not found'}, 404);
}
return entity;
})
This is borrowed from Laravel's Route-Model binding feature. Feel free to tweak it ๐
Seems like you are trying to use import { from } from 'rxjs'
here which does not exist as a standalone export anymore, use instead Observable.from
I came across this when updating to 3.0
and got the following error:
[ExceptionHandler] rxjs_1.from is not a function TypeError: rxjs_1.from is not a function at Function.<anonymous> (****\node_modules\@nestjs\typeorm\dist\typeorm-core.module.js:26:37)
[ ] 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.
Right now, TypeOrmModule.forFeature
only supports entities to inject into the Nest containers.
TypeOrmModule.forFeature
should be expanded to support subscribers and migrations
I really wanted to see this being possible:
import { Injectable } from '@nestjs/common'
import { EntitySubscriberInterface } from 'typeorm'
import { PubSub } from 'graphql-subscriptions'
@Injectable()
@EventSubscriber()
export class GlobalSubscriber implements EntitySubscriberInterface {
constructor(private readonly pubSub: PubSub) {}
...
I can't for example, declare my subscriber as injectable and use an injected PubSub instance, see the code above. Because they're actually initalized by TypeORM metadata system and are beyond reach from Nest Module System, unfortunately, for subscribers and migrations they have to be workarounded by using global state exported from a ES module, this is not ideal.
Nest version: 5.3.0
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.