I am trying to create a backend using NestJS and I am getting this error
ERROR [ExceptionsHandler] No metadata for "TransactionRepository" was found.
EntityMetadataNotFoundError: No metadata for "TransactionRepository" was found.
Everything is set up correctly. The entity is also set up correctly. What did I do wrong? Kindly help
transaction.repository.ts
import { EntityRepository, Repository } from "typeorm";
import { Transaction } from "../entities/transaction.entity";
#EntityRepository(Transaction)
export class TransactionRepository extends Repository<Transaction> {
}
transaction.service.ts
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { CreateTransactionDto } from '../dto/create-transaction.dto';
import { TransactionRepository } from '../repositories/transaction.repository';
#Injectable()
export class TransactionService {
constructor(
#InjectRepository(TransactionRepository) private transactionRepository: TransactionRepository,
){}
getAllTransactions() {
return [1, 2, 3, 4];
}
async createTransaction(transaction: CreateTransactionDto) {
return await this.transactionRepository.save(transaction);
}
}
According to this post: No metadata for "User" was found using TypeOrm
it looks like you have to modify this line in omrconfig.json and had ts:
"entities": ["src/**/**.entity{.ts,.js}"],
Related
the console says :
Nest can't resolve dependencies of the VisitService (?, DonorService). Please make sure that the argument VisitModel at index [0] is available in the VisitModule context.
Potential solutions:
If VisitModel is a provider, is it part of the current VisitModule?
If VisitModel is exported from a separate #Module, is that module imported within VisitModule?
this is vistit.service :
import { forwardRef, Inject, Injectable } from '#nestjs/common';
import { InjectModel } from '#nestjs/mongoose';
import { Model } from 'mongoose';
import { DonorVisitStatus } from 'src/constants/donor-visit-status.enum';
import { GetDateDifferenceHours } from 'src/utils';
import { DonorService } from '../donor/donor.service';
import { VisitDocument } from '../schemas/visit.schema';
import { CreateVisitInput } from './graphql/visit.input';
import { Visit } from './graphql/visit.type';
#Injectable()
export class VisitService {
constructor(
#InjectModel('Visit') private readonly visitModel: Model<VisitDocument>,
#Inject(forwardRef(() => DonorService)) private donorService: DonorService,
) {}
async findVisitById(visitId: string): Promise<VisitDocument | undefined> {
const visit = await this.visitModel
.findOne({ _id: visitId })
.populate('medicalCheckup')
.populate('phlebotomy')
.populate('donor');
return visit || undefined;
}
}
visit.module :
import { Module, forwardRef } from '#nestjs/common';
import { VisitService } from './visit.service';
import { VisitResolver } from './visit.resolver';
import { ConfigModule } from 'config/config.module';
import { MongooseModule } from '#nestjs/mongoose';
import { VisitSchema } from '../schemas/visit.schema';
import { DonorModule } from '../donor/donor.module';
#Module({
imports: [
MongooseModule.forFeature([{ name: 'Visit', schema: VisitSchema }], 'aidea_donation'),
ConfigModule,
forwardRef(() => DonorModule),
],
providers: [VisitService, VisitResolver],
exports: [VisitService],
})
export class VisitModule {}
i have checked it alot but i can't find any error
You use a named connection in MongooseModule.forFeature() so you need to use the same connection in the #InjectModel(). Change your #InjectModel() to #InjectModel('Visit', 'aidea_donation') and it should work
I'm trying to build an API with nest.js but I'm making use of vanilla javascript instead of the popular typescript. From the nest docs, I set up typeorm but I can't implement the example code in vanilla javascript, and for some reason, the javascript example isn't available on nest js docs.
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
#Injectable()
export class UsersService {
constructor(
#InjectRepository(User)
private usersRepository: Repository<User>,
) {}
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(id: string): Promise<User> {
return this.usersRepository.findOne(id);
}
async remove(id: string): Promise<void> {
await this.usersRepository.delete(id);
}
}
Any form of assistance would be much appreciated.
In the documentation, on the top right corner of the code example, generally you can click to switch between TS ans JS code example:
JS
import { Injectable, Dependencies } from '#nestjs/common';
import { getRepositoryToken } from '#nestjs/typeorm';
import { User } from './user.entity';
#Injectable()
#Dependencies(getRepositoryToken(User))
export class UsersService {
constructor(usersRepository) {
this.usersRepository = usersRepository;
}
findAll() {
return this.usersRepository.find();
}
findOne(id) {
return this.usersRepository.findOne(id);
}
async remove(id) {
await this.usersRepository.delete(id);
}
}
I'm doing a Nest.js program but I can't find my dependencies problem. I have searched quite a lot and I have found a lot of answers regarding this problem, but I can't figure out why my code isn´t working. So I have a product module which has his DTO´s, Entity, Controller, Service and module, besides it has an interface for its service.
ProductController
import { Controller, Get } from '#nestjs/common';
import { ProductServiceInterface } from './interface/product.service.interface'
#Controller('products')
export class ProductController {
constructor(private readonly productService: ProductServiceInterface) {}
#Get()
getHello(): string {
return this.productService.test();
}
}
ProductServiceInterface
import { Injectable } from '#nestjs/common';
import {
CreateProductInput,
CreateProductOutput,
} from '../dto/create-product.dto';
import { FindProductOutput } from '../dto/find-product.dto';
export interface ProductServiceInterface {
create(input: CreateProductInput): Promise<CreateProductOutput>;
findProduct(productId: string): Promise<FindProductOutput>;
test();
}
ProductService
import { Injectable } from '#nestjs/common';
import { ProductServiceInterface } from './interface/product.service.interface';
import {
CreateProductInput,
CreateProductOutput,
} from './dto/create-product.dto';
import { Product } from './entity/product.entity';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { FindProductOutput } from './dto/find-product.dto';
//import WooCommerce from '../../config/woocomerce.config';
#Injectable()
export class ProductService implements ProductServiceInterface {
constructor(
#InjectRepository(Product)
private productRepository: Repository<Product>,
) {}
public async create(
productDto: CreateProductInput,
): Promise<CreateProductOutput> {
const product = new Product();
product.name = productDto.name;
product.price = productDto.price;
product.imgUrl = productDto.imgUrl;
const savedProduct = await this.productRepository.save(product);
const productOutput = new CreateProductOutput();
productOutput.id = savedProduct.id;
return productOutput;
}
public async findProduct(idProduct: string): Promise<FindProductOutput> {
const fetchedProduct = await this.productRepository.findOne(idProduct);
const productOutput = new FindProductOutput();
productOutput.id = fetchedProduct.id;
productOutput.imgUrl = fetchedProduct.imgUrl;
productOutput.name = fetchedProduct.name;
productOutput.price = fetchedProduct.price;
return productOutput;
}
public test() {
return 'test'
// WooCommerce.get('products', {
// pero_page: 20,
// }).then((resp) => {
// return resp;
// });
}
}
ProductModule
import { ProductController } from './product.controller';
import { ProductService } from './product.service';
import { Product } from './entity/product.entity';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Module } from '#nestjs/common';
#Module({
imports: [TypeOrmModule.forFeature([Product])],
controllers: [ProductController],
providers: [ProductService],
})
export class ProductModule {}
AppModule
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '#nestjs/config';
import configuration from 'src/config/configuration';
import { TypeOrmModule } from '#nestjs/typeorm';
import { TypeOrmConfigService } from 'src/config/typeorm.config.service';
import { ProductModule } from './modules/product/product.module';
#Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
isGlobal: true,
}),
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService,
}),
ProductModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
I hope this code is enough for knowing where my mistake is, I don't like letting others just resolve this for me but I've been watching my code for hours and can't know how to resolve this dependencies problem.
Interfaces disappear at runtime and becomes {} or Object. Nest uses the parameter type metadata to determine what is supposed to be injected (usually via ClassType.name). You have two options to solve this
Use an abstract class instead of an interface. This makes the class still visible at runtime so ClassType.name still works.
Use #Inject('CustomToken') as the way to set the metadata for what Nest needs to inject. You then need to make sure register the custom provider using something like
{
provide: 'CustomToken',
useClass: ClassToBeUsed
}
Either of these methods should fix your issue.
Hi i have problem with my code.
import { Injectable } from '#angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { Http } from "#angular/http";
import 'rxjs'
#Injectable()
export class CarsService {
private apiUrl = "http://localhost:3000/api/cars";
constructor(private http : Http) { }
getCars() : Observable<Car[]> {
return this.http.get(this.apiUrl)
.map((res) => res.json())
}
}
With this code i have error:
this.http.get(...).map is not a function
but when i add:
import 'rxjs/add/operator/map'
Still have problem but error is:
Cannot read property 'map' of undefined
Can you help me? Thanks
As mentioned by others Http is deprecated, use HttpClient instead. HttpClient parses your response to an Object, so you remove the mapping of the response. Also, to avoid type checking errors, tell Angular what kind of response you are expecting.
So import HttpClientModule and add it to imports array, after BrowserModule. In your Service import HttpClient, inject it in your constructor and use it the following way:
import { Injectable } from '#angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { HttpClient } from "#angular/common/http";
import 'rxjs'
#Injectable()
export class CarsService {
private apiUrl = "http://localhost:3000/api/cars";
constructor(private httpClient : HttpClient) { }
getCars() : Observable<Car[]> {
// tell Angular you are expecting an array of 'Car'
return this.httpClient.get<Car[]>(this.apiUrl)
}
}
With angular5 HttpClient implementation already includes inner using of the map.so it works for you automatically.
just update it as
getCars() : Observable<Car[]> {
return this.http.get(this.apiUrl)
}
Also make sure you are using HttpClient instead of Http.
You can read more about this here
Edit your code
import { Injectable } from '#angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { Http } from "#angular/http";
#Injectable()
export class CarsService {
private apiUrl = "http://localhost:3000/api/cars";
constructor(private http : Http) { }
getCars() : Observable<Car[]> {
return this.http.get(this.apiUrl)
}
}
since it automatically parse the response as JSON. You don't have to explicitly parse it.
ngOnInit() {
this.loadCars();
}
loadCars() : void {
this.carsService.getCars().subscribe((cars) => {
this.cars = cars;
this.countTotalCost();
})
}
So i move this this.countTotalCost();
from ngOnInit to loadCars
and now .map its ok.
I have only this error: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'NaN'.
<div class="row" *ngIf="grossCost"> //this line error/error context
<div class="col-sm-12">
<div class="total-cost">
<p class="text-right">TOTAL GROSS COST: {{ grossCost}} PLN</p>
</div>
</div>
</div>
In my Angular 4 app I'm trying to get some data from an API. I'm using this article which explains how to do that, but I'm getting an exception:
TypeError: this.http.get(...).map is not a function
This is my code:
import { Injectable } from '#angular/core';
import { Http, Response, Headers } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { Person } from '../../../interfaces/Person';
import {configuration} from "../config";
#Injectable()
export class AdsService{
private baseUrl: string = configuration.serverUrl;
constructor(private http : Http){
}
getAll(): Observable<Person[]>{
let people$ = this.http
.get(`${this.baseUrl}/people`, {headers: this.getHeaders()})
.map(mapPeople);
return people$;
}
}
function mapPeople(response:Response): Person[]{
return response.json().results;
}
Any help will be profoundly appreciated!
I dont see the map method imported.
Add this to your imports
import rxjs/add/operator/map
You must import map in this file, for that you just need to add the following line:
import 'rxjs/add/operator/map';
OR
import 'rxjs/add/operators/map';
Also, if you are using Angular 5 or above, then the above imports have been sorted to :
import { map } from 'rxjs/operator';
OR
import { map } from 'rxjs/operators';
Add this and Enjoy !!! :-)