yarn // install
yarn db:dev:restart // start postgres in docker and push migrations
yarn start:dev // start api in dev mode
vladwulf / nestjs-api-tutorial Goto Github PK
View Code? Open in Web Editor NEWNestJs REST API tutorial for FreeCodeCamp
NestJs REST API tutorial for FreeCodeCamp
This line is decrepated:
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
It work with:
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
When i try to run the test for getBookmarks i get an error :
Unknown arg userId
in where.userId for type BookmarkWhereInput. Did you mean id
? Available args:
type BookmarkWhereInput {
AND?: BookmarkWhereInput | List
OR?: List
NOT?: BookmarkWhereInput | List
id?: IntFilter | Int
createdAt?: DateTimeFilter | DateTime
updatedAt?: DateTimeFilter | DateTime
title?: StringFilter | String
description?: StringNullableFilter | String | Null
link?: StringFilter | String
}
this is my prisma model :
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
hash String
firstName String?
lastName String?
bookmarks Bookmark[]
@@map("users")
}
model Bookmark {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
description String?
link String
userId Int
user User @relation(fields: [userId], references: [id])
@@map("bookmarks")
}
why i got this error?
Hello vlad, you are really amazing and I love you content very much, the way you tech, its really wonderful way of teaching,
love your videos,
and I have a question,
We have talked about refresh token and auth token,
Now I want to implement this with next.js for the frontend, and now how do I handle the refresh token request, and setting up dynamic contents for the authorized users ? and since it expires token in some time, so how to auto request the refresh token etc?
Can you please tell me how to do this? A guide on this,
This will save my life so much!
I am getting this error when trying to run nest js
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\shaun\node_modules@angular\core\fesm2015\core.mjs not supported.
Instead change the require of C:\Users\shaun\node_modules@angular\core\fesm2015\core.mjs to a dynamic import() which is available in all CommonJS modules.
at Object. (C:\Users\shaun\OneDrive\Documents\MY PROJECTS\Nestjs\tutorial- frecodecamp\bookmark-api\dist\prisma\prisma.service.js:13:16)
at Object. (C:\Users\shaun\OneDrive\Documents\MY PROJECTS\Nestjs\tutorial- frecodecamp\bookmark-api\dist\prisma\prisma.module.js:11:26)
at Object. (C:\Users\shaun\OneDrive\Documents\MY PROJECTS\Nestjs\tutorial- frecodecamp\bookmark-api\dist\app.module.js:14:25)
at Object. (C:\Users\shaun\OneDrive\Documents\MY PROJECTS\Nestjs\tutorial- frecodecamp\bookmark-api\dist\main.js:4:22)
I have a probleme to connect to the postgres on docker.
I have the env ::
DATABASE_URL="postgresql://postgres:123@localhost:5432/nest?schema=public"
and the docker-compose ::
version: '3.8' services: dev-db: image: postgres:13 ports: - 5434:5432 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: 123 POSTGRES_DB: nest networks: - freecodecamp networks: freecodecamp:
I do on the terminal ::
npx prisma migrate dev
i have ::
Error: P1001: Can't reach database server at localhost
:5432
expectBodyContains doesn't seem to care about where the provided value appears. In case the code is failing for some reason but by chance the user id is same as the bookmark id, then the test will succeed. This is particularly a likely unwanted outcome, if cleanDb also resets all auto increment values. (first user and bookmark will have 1 as id).
For instance, I have also stored the userId in pactum at "Get me" test and tested against userId at "should get bookmark by id", which succeeded. Even worse, the number may match with other fields, e.g. createdAt, updatedAt etc.
.expectJsonMatch({id: '$S{bookmarkId}'}) would have been the correct test here.
The strategy validate
method is using only id
in the where clause but when doing the call for /users/me
it getting the error:
[Nest] 41843 - 04/11/2023, 8:49:30 PM ERROR [ExceptionsHandler]
Invalid `this.prisma.user.findUnique()` invocation in
/Users/edsonmartins/dev/nest/freeCodeCamp/GHTA143_b-s/nestjs-api-tutorial/src/auth/strategy/jwt.strategy.ts:17:41
14 });
15 }
16 async validate(payload: { sub: number; email: string }) {
→ 17 const user = await this.prisma.user.findUnique({
where: {
? id?: Int,
? email?: String
}
})
Argument where of type UserWhereUniqueInput needs at least one argument. Available args are listed in green.
Note: Lines with ? are optional.
Looking to solve this, I have changed my local code as:
async validate(payload: { sub: number; email: string }) {
const user = await this.prisma.user.findUnique({
where: {
id: payload.sub,
email: payload.email,
},
});
delete user.hash;
return user;
}
or using findFirst instead of using findUnique.
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
hash String
firstName String?
lastName String?
bookmarks Bookmark[]
@@map("users")
}
Could you share if the approach using findUnique
with both fields or findFirst
with id
only is correct or is there something more to use findUnique
with only the id
?
I am creating this issue just in case if someone is following the nodejs tutorial on freecodecamp and facing issue while implementing the JWT strategy.
mikenicholson/passport-jwt#153
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'), //instead of ExtractJwt.fromAuthHeaderAsBearerToken()
ignoreExpiration: true,
});
}
validate(payload: any) {
console.log(payload);
return payload;
}
While calling the request you can normally pass Authorization
header as Bearer ${token}
Dear Vlad,
I saw your video on Youtube (Free Code Camp one) and the tutorial is so cool - anyway - the readme file could be a bit more comprehensive with explanation how to really run the whole environment :-)
Thank you!
Jaroslav
I have been trying to reproduce the validation part using dtos and global pipes but for some reason the whitelist option is not working. I know there have been ground breaking changes with nest, and their document hasn't been updated for the same, but the issue persists.
Here is my auth.dto.ts:
import { IsEmail, IsNotEmpty, IsString } from "class-validator"
export class AuthDto {
@IsEmail()
@IsNotEmpty()
email: string;
@IsString()
@IsNotEmpty()
password: string;
}
Here is my main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
}));
await app.listen(3333);
}
bootstrap();
Encounter with this problem at all files.
the import from the tutorial
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
Is not working as expected, instead when I import like below as per the documentation it works fine:
import { Prisma } from '@prisma/client';
// and try to match error instance in this way
if (error instanceof Prisma.PrismaClientKnownRequestError) {
console.log(error.message);
if (error.code === 'P2002') {
throw new ForbiddenException('Credentials taken');
}
}
Hope this helps if anyone following along faces the same issue.
Doc link referred: https://www.prisma.io/docs/concepts/components/prisma-client/handling-exceptions-and-errors
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.