how to fix this message angular observable - node.js

I have a little probleme, I use the node(express) and angular,
I want display all classes in angular but it's show an error like this
and it's not show json of back-end, what is wrong I don't understand
Return of method http get clasRoutes.js
res.json({ success: true, classes: postQuery, total: nbClasses });
Clas.interface.ts
export interface Clas {
room: string;
img?: string;
}
Clas.service.ts
private urlGetClasses = environment.url + 'classes';
constructor( private http: HttpClient ) { }
getClass(): Observable<Clas[]> {
return this.http.get(this.urlGetClasses).pipe(map(a => console.log(a)));
}
Clas.component.ts
public clas: Clas[] = [];
constructor(private clasService: ClasService) {}
ngOnInit() {
this.getClass().subscribe(res => {
this.clas = res.classes
});
}
private getClass(): Observable < Clas[] > {
return this.clasService.getClass().pipe(tap((value) => {
console.log(value)
}));
}
Clas.component.html
<p *ngFor="let cla of clas">
zefd {{cla.room}}
</p>

The problem is with Clas.service.ts. In your getClass() method, you are mapping to void as the return type of console.log is void; i.e. you are returning void whereas you've specified the return type of getClas() is Observable<Clas[]>. Therefore, you need to change your getClas() method to:
getClass(): Observable<Clas[]> {
return this.http.get(this.urlGetClasses);
}
Or as Nikola mentioned, you can use tap to log like so:
private getClass(): Observable<Clas[]> {
return this.clasService.getClass().pipe(tap((value) => {console.log(value)}));
}

There is new RxJS syntax. You should write it as
private getClass(): Observable<Clas[]> {
return this.clasService.getClass().pipe(tap((value) => {console.log(value)}));
}
make sure you import pipe and tap from rxjs.

Related

NestJS lifecycle methods invoked without implementing their interface

I am having a small question about NestJS. In my code, there is a service which looks something like:
`
import { Inject, Injectable } from '#nestjs/common';
import neo4j, { Driver, int, Result, Transaction } from 'neo4j-driver';
import { Neo4jConfig } from './neo4j-config.interface';
import { NEO4J_CONFIG, NEO4J_DRIVER } from './neo4j.constants';
#Injectable()
export class Neo4jService {
constructor(
#Inject(NEO4J_CONFIG) private readonly config: Neo4jConfig,
#Inject(NEO4J_DRIVER) private readonly driver: Driver,
) {}
onApplicationBootstrap() {
console.log('Hello');
}
getDriver(): Driver {
return this.driver;
}
getConfig(): Neo4jConfig {
return this.config;
}
int(value: number) {
return int(value);
}
beginTransaction(database?: string): Transaction {
const session = this.getWriteSession(database);
return session.beginTransaction();
}
getReadSession(database?: string) {
return this.driver.session({
database: database || this.config.database,
defaultAccessMode: neo4j.session.READ,
});
}
getWriteSession(database?: string) {
return this.driver.session({
database: database || this.config.database,
defaultAccessMode: neo4j.session.WRITE,
});
}
read(
cypher: string,
params?: Record<string, unknown>,
databaseOrTransaction?: string | Transaction,
): Result {
if (databaseOrTransaction instanceof Transaction) {
return (<Transaction>databaseOrTransaction).run(cypher, params);
}
const session = this.getReadSession(<string>databaseOrTransaction);
return session.run(cypher, params);
}
write(
cypher: string,
params?: Record<string, unknown>,
databaseOrTransaction?: string | Transaction,
): Result {
if (databaseOrTransaction instanceof Transaction) {
return (<Transaction>databaseOrTransaction).run(cypher, params);
}
const session = this.getWriteSession(<string>databaseOrTransaction);
return session.run(cypher, params);
}
private onApplicationShutdown() {
console.log('Goodbye')
return this.driver.close();
}
}
`
Then in my main.ts file I have this method called:
`
await app.listen(port);
`
As you can see my service does not implement neither onApplicationBootstrap nor onApplicationShutdown.
How does it come that those methods still get invoked? Should I implement onApplicationBootstrap and onApplicationShutdown or not?
As you can also see I' d like that my onApplicationBootstrap is a private method which would not be possible if I implement the interface.
So, I would like to ask you:
Why the two lifecycle methods get called event without implementing the interface?
Should I implement those interfaces at all or just go on and use the methods which would allow me to define them as private?
I expected those methods to not work without implementing the interfaces
The Typescript interface is there to help us as devs. It doesn't exist at runtime, there's no information about it, so the only thing Nest can do is just check "Hey, does this class have the onModuleInit method?" If yes, add it to a list of classes to call onModuleInit. Do the same with the other lifecycle methods.
The interfaces aren't explicitly necessary, but they do give us devs a better idea of the class by just looking at the export class... line because we can see what is implemented/extended.

Why it doesn't use "<Event>" instead of "<T extends Event>"?

I am just wondering to know if there is any reason the following code uses <T extends Event> instead of Event> in this line export abstract class Publisher` of the code?
import { Stan } from 'node-nats-streaming';
import { Subjects } from './subjects';
interface Event {
subject: Subjects;
data: any;
}
export abstract class Publisher<T extends Event> {
abstract subject: T['subject'];
protected client: Stan;
constructor(client: Stan) {
this.client = client;
}
publish(data: T['data']): Promise<void> {
return new Promise((resolve, reject) => {
this.client.publish(this.subject, JSON.stringify(data), (err) => {
if (err) {
return reject(err);
}
console.log('Event published to subject', this.subject);
resolve();
});
});
}
}
In order to understand the difference, you need to understand what both things do.
<T extends Event>
The T is the name of the generic (this can be anything) extends Event is there so Typescript knows that you only want to allow generics that are of type Event or an implementation of it.
<Event>
Like said above a generic can be any word, like Event, you are basicly making a generic without any restrictions, and it will be typed as the type you passed it in.

TypeScript - Repository pattern with Sequelize

I'm converting my Express API Template to TypeScript and I'm having some issues with the repositories.
With JavaScript, I would do something like this:
export default class BaseRepository {
async all() {
return this.model.findAll();
}
// other common methods
}
import BaseRepository from './BaseRepository';
import { User } from '../Models';
export default class UserRepository extends BaseRepository {
constructor() {
super();
this.model = User;
}
async findByEmail(email) {
return this.model.findOne({
where: {
email,
},
});
}
// other methods
Now, with TypeScript, the problem is that it doesn't know the type of this.model, and I can't pass a concrete model to BaseRepository, because, well, it is an abstraction. I've found that sequelize-typescript exports a ModelCtor which declares all the static model methods like findAll, create, etc., and I also could use another sequelize-typescript export which is Model to properly annotate the return type.
So, I ended up doing this:
import { Model, ModelCtor } from 'sequelize-typescript';
export default abstract class BaseRepository {
protected model: ModelCtor;
constructor(model: ModelCtor) {
this.model = model;
}
public async all(): Promise<Model[]> {
return this.model.findAll();
}
// other common methods
}
import { Model } from 'sequelize-typescript';
import BaseRepository from './BaseRepository';
import { User } from '../Models';
export default class UserRepository extends BaseRepository {
constructor() {
super(User);
}
public async findByEmail(email: string): Promise<Model | null> {
return this.model.findOne({
where: {
email,
},
});
}
// other methods
}
Ok, this works, TypeScript doesn't complain about methods like findOne or create not existing, but that generates another problem.
Now, for example, whenever I get a User from the repository, if I try to access one of its properties, like user.email, TypeScript will complain that this property does not exist. Of course, because the type Model does not know about the specifics of each model.
Ok, it's treason generics then.
Now BaseRepository uses a generic Model type which the methods also use:
export default abstract class BaseRepository<Model> {
public async all(): Promise<Model[]> {
return Model.findAll();
}
// other common methods
}
And the concrete classes pass the appropriate model to the generic type:
import BaseRepository from './BaseRepository';
import { User } from '../Models';
export default class UserRepository extends BaseRepository<User> {
public async findByEmail(email: string): Promise<User | null> {
return User.findOne({
where: {
email,
},
});
}
// other methods
}
Now IntelliSense lights up correctly, it shows both abstract and concrete classes methods and the model properties (e.g. user.email).
But, as you have imagined, that leads to more problems.
Inside BaseRepository, where the methods use the Model generic type, TypeScript complains that 'Model' only refers to a type, but is being used as a value here. Not only that, but TypeScript also doesn't know (again) that the static methods from the model exist, like findAll, create, etc.
Another problem is that in both abstract and concrete classes, as the methods don't use this anymore, ESLint expects the methods to be static: Expected 'this' to be used by class async method 'all'. Ok, I can just ignore this rule in the whole file and the error is gone. It would be even nicer to have all the methods set to static, so I don't have to instantiate the repository, but maybe I'm dreaming too much.
Worth mentioning that although I can just silence those errors with // #ts-ignore, when I execute this, it doesn't work: TypeError: Cannot read property 'create' of undefined\n at UserRepository.<anonymous>
I researched a lot, tried to make all methods static, but static methods can't reference the generic type (because it is considered an instance property), tried some workarounds, tried to pass the concrete model in the constructor of BaseRepository along with the class using the generic type, but nothing seems to work so far.
In case you want to check the code: https://github.com/andresilva-cc/express-api-template/tree/main/src/App/Repositories
EDIT:
Found this: Sequelize-Typescript typeof model
Ok, I removed some unnecessary code from that post and that kinda works:
import { Model } from 'sequelize-typescript';
export default abstract class BaseRepository<M extends Model> {
constructor(protected model: typeof Model) {}
public async all(attributes?: string[]): Promise<M[]> {
// Type 'Model<{}, {}>[]' is not assignable to type 'M[]'.
// Type 'Model<{}, {}>' is not assignable to type 'M'.
// 'Model<{}, {}>' is assignable to the constraint of type 'M', but 'M' could be instantiated with a different subtype of constraint 'Model<any, any>'.
return this.model.findAll({
attributes,
});
}
import BaseRepository from './BaseRepository';
import { User } from '../Models';
export default class UserRepository extends BaseRepository<User> {
constructor() {
super(User);
}
}
I mean, if I put some // #ts-ignore it at least executes, and IntelliSense lights up perfectly, but TypeScript complains.
We faced the same problem. The solution was to declare returning types with an interface that an abstract repository class implements.
Code for the interface:
export type RepoResult<M> = Promise<Result<M | undefined, RepoError | undefined>>;
export interface IRepo<M> {
save(model: M): RepoResult<M>;
findById(id: string): RepoResult<M>;
search(parameterName: string, parameterValue: string, sortBy: string, order: number, pageSize: number, pageNumber: number): RepoResult<M[]>;
getAll(): RepoResult<M[]>;
deleteById(id: string): RepoResult<M>;
findByIds(ids: string[]): RepoResult<M[]>;
deleteByIds(ids: string[]): RepoResult<any>;
};
Code for the abstract class:
export abstract class Repo<M extends sequelize.Model> implements IRepo<M> {
protected Model!: sequelize.ModelCtor<M>;
constructor(Model: sequelize.ModelCtor<M>) {
this.Model = Model;
}
public async save(doc: M) {
try {
const savedDoc = await doc.save();
return Result.ok(savedDoc);
} catch (ex: any) {
logger.error(ex);
return Result.fail(new RepoError(ex.message, 500));
}
}
public async findById(id: string) {
try {
const doc = await this.Model.findOne({where: {
id: id
}});
if (!doc) {
return Result.fail(new RepoError('Not found', 404));
}
return Result.ok(doc);
} catch (ex: any) {
return Result.fail(new RepoError(ex.message, 500));
}
}
}
Hope it helps. Have a nice day:)
EDIT:
Result is a class that looks like this:
export class Result<V, E> {
public isSuccess: boolean;
public isFailure: boolean;
private error: E;
private value: V;
private constructor(isSuccess: boolean, value: V, error: E) {
if (isSuccess && error) {
throw new Error('Successful result must not contain an error');
} else if (!isSuccess && value) {
throw new Error('Unsuccessful error must not contain a value');
}
this.isSuccess = isSuccess;
this.isFailure = !isSuccess;
this.value = value;
this.error = error;
}
public static ok<V>(value: V): Result<V, undefined> {
return new Result(true, value, undefined);
}
public static fail<E>(error: E): Result<undefined, E> {
return new Result(false, undefined, error);
}
public getError(): E {
if (this.isSuccess) {
throw new Error('Successful result does not contain an error');
}
return this.error;
}
public getValue(): V {
if (this.isFailure) {
throw new Error('Unsuccessful result does not contain a value');
}
return this.value;
}
}
RepoError class:
type RepoErrorCode = 404 | 500;
export class RepoError extends Error {
public code: RepoErrorCode;
constructor(message: string, code: RepoErrorCode) {
super(message);
this.code = code;
}
}
RepoResult type:
export type RepoResult<M> = Promise<Result<M | undefined, RepoError | undefined>>;
You can find more info on the pattern at the link below:
https://khalilstemmler.com/articles/enterprise-typescript-nodejs/functional-error-handling/

I'd like to DI for repository interface and service interface like Spring using typedi

I'd like to DI for repository interface and service interface like Spring using typedi.
Below code (example code of DI for repository) is working correctly when calling api.
Repository
import { Service } from "typedi";
import { EntityRepository, Repository } from "typeorm";
import { User } from "../entity/User";
export interface IUserRepository {
findAllUsers();
findUserByUserId(id: number);
addUser(user: any);
removeUserByUserId(user: any);
}
#Service()
#EntityRepository(User)
export class UserRepository
extends Repository<User>
implements IUserRepository {
findAllUsers() {
return this.find();
}
findUserByUserId(id: number) {
return this.findOne({ id });
}
addUser(user: any) {
return this.save(user);
}
removeUserByUserId(user: any) {
return this.remove(user);
}
}
Service
import { Service } from "typedi";
import { InjectRepository } from "typeorm-typedi-extensions";
import { User } from "../entity/User";
import { UserRepository } from "../repository/userRepository";
export interface IUserService {
all();
one(id: any);
save(user: any);
remove(id: any);
}
#Service()
export class UserService implements IUserService {
#InjectRepository(User)
private userRepository: UserRepository;
async all() {
return this.userRepository.findAllUsers();
}
async one(id: any) {
let user = await this.userRepository.findUserByUserId(id);
if (typeof user === "undefined") {
throw new Error(`userId ${id} is not found.`);
}
return user;
}
async save(user: any) {
return this.userRepository.addUser(user);
}
async remove(id: any) {
let userToRemove = await this.userRepository.findUserByUserId(id);
if (typeof userToRemove === "undefined") {
throw new Error(`userId ${id} is not found.`);
}
return this.userRepository.removeUserByUserId(userToRemove);
}
}
However, when I'd like to inject repository using interface, it does not work correctly and occur the error message.
The build is succes. The error message is occur when calling api
In addition, error message are different for the first time and the second time later when call api.
like this
Repository
import { Service } from "typedi";
import { InjectRepository } from "typeorm-typedi-extensions";
import { User } from "../entity/User";
import { UserRepository } from "../repository/userRepository";
...
#Service()
export class UserService implements IUserService {
#InjectRepository(User)
private userRepository: UserRepository;
async all() {
return this.userRepository.findAllUsers();
}
...
}
Error message of first time.
{
"name": "CustomRepositoryNotFoundError",
"message": "Custom repository Object was not found. Did you forgot to put #EntityRepository decorator on it?",
"stack": "CustomRepositoryNotFoundError: Custom repository Object was not found. Did you forgot to put #EntityRepository decorator on it? (The following is omitted)"
}
Error message of second time later.
{
"name": "TypeError",
"message": "Cannot read property 'all' of undefined",
"stack": "TypeError: Cannot read property 'all' of undefined(The following is omitted)"
}
Service does not work well either.
Below code is success code.
Controller
import {
Get,
JsonController,
OnUndefined,
Param,
Post,
Body,
Delete,
} from "routing-controllers";
import { Inject, Service } from "typedi";
import { UserService } from "../service/userService";
#Service()
#JsonController("/users")
export class UserRestController {
#Inject()
private userService: UserService;
#Get("/")
getAll() {
return this.userService.all();
}
#Get("/:id")
#OnUndefined(404)
getOne(#Param("id") id: number) {
return this.userService.one(id);
}
#Post("/")
add(#Body() user: any) {
return this.userService.save(user);
}
#Delete("/:id")
delete(#Param("id") id: number) {
return this.userService.remove(id);
}
}
But the below is not work well.
In this case, even the build does not work.
Controller
import {
Get,
JsonController,
OnUndefined,
Param,
Post,
Body,
Delete,
} from "routing-controllers";
import { Inject, Service } from "typedi";
import { IUserService } from "../service/userService";
#Service()
#JsonController("/users")
export class UserRestController {
#Inject()
private userService: IUserService;
#Get("/")
getAll() {
return this.userService.all();
}
#Get("/:id")
#OnUndefined(404)
getOne(#Param("id") id: number) {
return this.userService.one(id);
}
#Post("/")
add(#Body() user: any) {
return this.userService.save(user);
}
#Delete("/:id")
delete(#Param("id") id: number) {
return this.userService.remove(id);
}
}
Error Message
CannotInjectValueError: Cannot inject value into "UserRestController.userService". Please make sure you setup reflect-metadata properly and you don't use interfaces without service tokens as injection value.
As described at the beginning, I'd like to DI for repository interface and service interface like Spring using typedi.
TypeDI cannnot using like this?
or my code is wrong?
Please help me.
Thank you.
Interfaces are ephemeral, they don't actually exist when your code is running doing its job, they exist only when you write the code. Classes, on the other hand, are pretty much tangible, they always exist. That's why when you use UserService class, it works, but when you use IUserService interface, it doesn't work.
The error you are getting tells you something useful:
Please make sure […] you don't use interfaces without service tokens as injection value.

In nestjs, is it possible to specify multiple handlers for the same route?

Is it possible to specify multiple handler for the same route?
Any HTTP GET request to the /test route should call the get handler unless the query string watch === '1', in which case it should call the watch handler instead.
import { Controller, Get } from '#nestjs/common';
#Controller('test')
export class TestController {
#Get()
get(){
return 'get'
}
#Get('?watch=1')
watch(){
return 'get with watch param'
}
}
As the framework does not seem to support this, I was hoping to be able to write a decorator to abstract this logic.
ie.
import { Controller, Get } from '#nestjs/common';
import { Watch } from './watch.decorator';
#Controller('test')
export class TestController {
#Get()
get(){
return 'get'
}
#Watch()
watch(){
return 'get with watch param'
}
}
Can this be done? Can anyone point me to the right direction?
I would try to keep the complexity low and simply implement two functions.
#Controller('test')
export class TestController {
myService: MyService = new MyService();
#Get()
get(#Query('watch') watch: number) {
if (watch) {
return myService.doSomethingB(watch);
} else {
return myService.doSomethingA();
}
}
}
export class MyService {
doSomethingA(): string {
return 'Do not watch me.'
}
doSomethingB(watch: number): string {
return 'Watch me for ' + watch + ' seconds.'
}
}

Resources