Giter VIP home page Giter VIP logo

nestjs-realworld-example-app's Issues

How to mock repositories during unit testing

In the example at https://github.com/mikro-orm/nestjs-realworld-example-app/blob/master/src/tag/tag.controller.spec.ts you are initializing mikroorm with the same config for the database as actually running the app. That seems odd to me.

What is the proper way during unit tests to initialize mikroorm, grab my repository from the IoC container and spy/mock its methods? In my case I just want to mock that and not my service as my service contains my business logic. Thanks.

Repository or em injection

I hope you dont mind asking me here, didnt know any other way...

First of all mikro-orm is amazing and really enjoy working with it so far! Great job!

What is recommend and why?
Injecting all the repositories that you need inside a service OR just injecting the Entity Manager and getting the appropriate repo with getRepository?

Thanks alot

wrap() function mocking with jest

Cheers!
First of all, thank you for this awesome ORM!!
I am trying to mock wrap() function. So long I'v tried several ways to do so, unsuccessfully.
Also noticed there is no example for that on this repository, could you please provide an example?

How do I use an EntityManager or EntityRepository outside of a module

My project directory is as follows

├── src
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── common
│   │   ├── pipes
│   │   │   └── validation.pipe.ts
│   │   └── validators
│   │       ├── Is-valid-city.ts
│   │       └── Is-valid-provincial.ts
│   ├── config
│   │   ├── configuration.ts
│   │   ├── db-mysql.module.ts
│   │   └── env
│   │       └──default.yaml
│   ├── main.ts
│   ├── migrations
│   └── modules
│       └── districts
│          ├── districts.controller.ts
│          ├── districts.module.ts
│          ├── districts.service.ts
│          ├── dto
│          └── entities
├── tsconfig.build.json
└── tsconfig.json

For special reasons, I need a custom validator, and to query the database in the validator, I put the custom validators under /src/common/validators, The code of is-valid-provincial.ts Is as follows:

@ValidatorConstraint({ async: true })
export class IsValidProvincialConstraint
  implements ValidatorConstraintInterface
{
  constructor(
    @InjectRepository(DistrictsEntity)
    private readonly dr: EntityRepository<DistrictsEntity>,
  ) {}
  async validate(id: string) {
    const provincial = await this.dr.findOne({ id, level: 2 });
    return Boolean(provincial);
  }
}

export function IsValidProvincial(validationOptions?: ValidationOptions) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsValidProvincialConstraint,
    });
  };
}

But every time I got an error, I couldn't find the findOne method for Entity, even though I used service
image

What am I supposed to do here? I hope you can help me. Thank you very much

`GET /api/articles` returns wrong results

I cloned the example and changed nothing.

This is my current article table in the database

Screen Shot 2020-04-27 at 14 40 52

And this is what GET /api/articles returns
Screen Shot 2020-04-27 at 14 41 26

It just returns the first article three times. I'm new to nestjs and mikro-orm, could you help me out?

The app uses global EntityManager instance on debugging

Hi,
I faced interesting issue while trying out this sample app. The issue is that the application throws the following error only when a debugger is attached to the app:

ERROR [ExceptionsHandler] Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead.
ValidationError: Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead.
    at Function.cannotUseGlobalContext (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/node_modules/@mikro-orm/core/errors.js:83:16)
    at SqlEntityManager.getContext (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/node_modules/@mikro-orm/core/EntityManager.js:751:44)
    at SqlEntityManager.createQueryBuilder (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/node_modules/@mikro-orm/knex/SqlEntityManager.js:15:30)
    at SqlEntityRepository.createQueryBuilder (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/node_modules/@mikro-orm/knex/SqlEntityRepository.js:15:24)
    at ArticleService.<anonymous> (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/src/article/article.service.ts:27:8)
    at Generator.next (<anonymous>)
    at /Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/dist/article/article.service.js:20:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/dist/article/article.service.js:16:12)
    at ArticleService.findAll (/Users/user/Documents/nestjs-realworld-example-app2/nestjs-realworld-example-app/dist/article/article.service.js:39:16)

When I start the app without a debugger, it works fine.

I've investigated this problem and found out that the issue is related to Node.js 18.x. I tested the app on Node.js v18.6 and v16.15 and the issue was reproduced only on 18th version. As I understood from my investigation, on Node 18, the currentRequestContext function sometimes returns undefined instead of the current store.
Then I also faced the same problem on my own app while migrating to the 5th version of the ORM, so this issue may not be specific only to the sample application.

Steps to reproduce

Prerequisites: Node.js 18.x

  1. Configure RequestContext support in your app (nestjs-realworld-example-app is already configured)
  2. Run the app in debug mode using yarn start:debug command or via VS Code scenario:
        {
            "name": "Launch via yarn",
            "request": "launch",
            "runtimeArgs": [
                "start"
            ],
            "runtimeExecutable": "yarn",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "node"
        }
    
  3. If the app was started in the terminal, attach a debugger to the app (Google Chrome or VS Code, etc)
  4. Send the request http://localhost:3000/api/articles

NestJS custom decorator not called

Hello Micael Levi .
Sorry about that , but i only found this way to contact you regarding the issue i posted on stackoverflow.
Could you please have a look.
I'm quite sure that when it's taking me couple of day to find the solution , you could solve it in 5 minutes .
I provided the github repo as you asked.

NestJS custom decorator not called
https://stackoverflow.com/q/73932793/14052942?sem=2

Cannot use import statement outside a module Error, when enabling tsNode in mikro-orm.config.ts

Full error :

nestjs-realworld-example-app/src/article/article.entity.ts:1
import { ArrayType, Collection, Entity, EntityDTO, ManyToOne, OneToMany, PrimaryKey, Property, wrap } from '@mikro-orm/core';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1159:20)
    at Module._compile (node:internal/modules/cjs/loader:1203:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1293:10)
    at Module.load (node:internal/modules/cjs/loader:1096:32)
    at Function.Module._load (node:internal/modules/cjs/loader:935:12)
    at Module.require (node:internal/modules/cjs/loader:1120:19)
    at require (node:internal/modules/helpers:112:18)
    at Function.requireFrom (nestjs-realworld-example-app/node_modules/@mikro-orm/core/utils/Utils.js:716:70)
    at Function.options.dynamicImportProvider.options.dynamicImportProvider [as dynamicImportProvider] (nestjs-realworld-example-app/node_modules/@mikro-orm/core/utils/ConfigurationLoader.js:225:34)

Can't generate entities

When I run yarn mikro-orm generate-entities --dump
It throw error

Error: Cannot find module 'C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\@mikro-orm\entity-generator'
Require stack:
- C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\__fake.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\node_modules\@cspotcode\source-map-support\source-map-support.js:811:30)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at Function.requireFrom (C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\node_modules\@mikro-orm\core\utils\Utils.js:692:70)    
    at Function.options.dynamicImportProvider.options.dynamicImportProvider [as dynamicImportProvider] (C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\node_modules\@mikro-orm\core\utils\ConfigurationLoader.js:219:34)
    at Function.dynamicImport (C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\node_modules\@mikro-orm\core\utils\Utils.js:713:32)  
    at Object.handler (C:\Users\user\Downloads\_git\nodejs-api\nestjs-realworld-example-app\node_modules\@mikro-orm\cli\commands\GenerateEntitiesCommand.js:44:56)
    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\user\\Downloads\\_git\\nodejs-api\\nestjs-realworld-example-app\\__fake.js'
  ]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.