GithubHelp home page GithubHelp logo

lujakob / nestjs-realworld-example-app Goto Github PK

View Code? Open in Web Editor NEW
2.9K 32.0 614.0 1.41 MB

Exemplary real world backend API built with NestJS + TypeORM / Prisma

Home Page: https://realworld.io/

JavaScript 0.14% TypeScript 98.60% Shell 1.26%
nestjs typeorm prisma

nestjs-realworld-example-app's Introduction

Node/Express/Mongoose Example App

Build Status

NestJS codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.


Getting started

Installation

Clone the repository

git clone https://github.com/lujakob/nestjs-realworld-example-app.git

Switch to the repo folder

cd nestjs-realworld-example-app

Install dependencies

npm install

Copy config file and set JsonWebToken secret key

cp src/config.ts.example src/config.ts

Database

The codebase contains examples of two different database abstractions, namely TypeORM and Prisma.

The branch master implements TypeORM with a mySQL database.

The branch prisma implements Prisma with a mySQL database.


TypeORM

Create a new mysql database with the name nestjsrealworld
(or the name you specified in the ormconfig.json)

Copy TypeORM config example file for database settings

cp ormconfig.json.example

Set mysql database settings in ormconfig.json

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "your-mysql-username",
  "password": "your-mysql-password",
  "database": "nestjsrealworld",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": true
}

Start local mysql server and create new database 'nestjsrealworld'

On application start, tables for all entities will be created.


Prisma

To run the example with Prisma checkout branch prisma, remove the node_modules and run npm install

Create a new mysql database with the name nestjsrealworld-prisma (or the name you specified in prisma/.env)

Copy prisma config example file for database settings

cp prisma/.env.example prisma/.env

Set mysql database settings in prisma/.env

DATABASE_URL="mysql://USER:PASSWORD@HOST:PORT/DATABASE"

To create all tables in the new database make the database migration from the prisma schema defined in prisma/schema.prisma

npx prisma migrate save --experimental
npx prisma migrate up --experimental

Now generate the prisma client from the migrated database with the following command

npx prisma generate

The database tables are now set up and the prisma client is generated. For more information see the docs:


NPM scripts

  • npm start - Start application
  • npm run start:watch - Start application in watch mode
  • npm run test - run Jest test runner
  • npm run start:prod - Build application

API Specification

This application adheres to the api specifications set by the Thinkster team. This helps mix and match any backend with any other frontend without conflicts.

Full API Spec

More information regarding the project can be found here https://github.com/gothinkster/realworld


Start application

  • npm start
  • Test api with http://localhost:3000/api/articles in your favourite browser

Authentication

This applications uses JSON Web Token (JWT) to handle authentication. The token is passed with each request using the Authorization header with Token scheme. The JWT authentication middleware handles the validation and authentication of the token. Please check the following sources to learn more about JWT.


Swagger API docs

This example repo uses the NestJS swagger module for API documentation. NestJS Swagger - www.swagger.io

nestjs-realworld-example-app's People

Contributors

arbassic avatar dependabot[bot] avatar lujakob avatar malkaviano avatar mcantonbul avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestjs-realworld-example-app's Issues

'aticles' mispelled lead to routes not protected

While playing with nestjs realworld, I found out that you can create post without user authenticated due to misspelled aticles in article.module.ts https://github.com/lujakob/nestjs-realworld-example-app/blob/master/src/article/article.module.ts#L24-L27

Due to this.userRepository.findOne(userId) where userId is null, return the first user instead of throwing an error, it doesn't help detecting that the user does not exist.

I recommend using this.userRepository.findOne({ where: { id: userId } });
See this TypeORM issues: typeorm/typeorm#2500

Using sha256 isn't secure for password hashing

sha256 is just a message digest, so it really shouldn't be used as an example for password hashing.

You can use argon2 though, which is considered the best current password hashing algorithm.

this.password = crypto.createHmac('sha256', this.password).digest('hex');

const argon2 = require('argon2');
 
try {
  this.password = await argon2.hash("password");
} catch (err) {
  //...
}

https://www.npmjs.com/package/argon2

What is the RO sufix in the interfaces?

Hello, I have a questions about the naming of the interfaces used in the project.

What exactly is the sufix RO, in the article for example, (ArticleData & ArticleRO)

I'm sorry to bother with that, but a literally can not find anything about it

Question about the 'RO' naming convention in the entity interfaces

I'm writing my first nestjs app (first node application for that matter) and am using this repo as one way to approach figuring out my best practices, etc. I was curious what the RO in the various interface objects stood for.

e.g. https://github.com/lujakob/nestjs-realworld-example-app/blob/2b56fb43bb99ad18cef26dcd70882b4e7c83d96d/src/article/article.interface.ts

Is it Return Object or something similar? I hate following conventions when I don't know what something means and can't explain to someone else!

npm run start:prod error

I want to start prod this following error.
[Nest] 92672 - 2019-06-09 09:49 [NestFactory] Starting Nest application...
[Nest] 92672 - 2019-06-09 09:49 [InstanceLoader] TypeOrmModule dependencies initialized +131ms
[Nest] 92672 - 2019-06-09 09:49 [TypeOrmModule] Unable to connect to the database. Retrying (1)... +105ms
/Users/lee/Sites/demo/nestjs-realworld-example-app/src/article/article.entity.ts:1
(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column, OneToOne, ManyToOne, OneToMany, JoinColumn, AfterUpdate, BeforeUpdate } from 'typeorm';
^^^^^^

SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Function.PlatformTools.load (/Users/lee/Sites/demo/nestjs-realworld-example-app/node_modules/_typeorm@0.2.18@typeorm/platform/PlatformTools.js:107:28)
[Nest] 92672 - 2019-06-09 09:49 [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3025ms
/Users/lee/Sites/demo/nestjs-realworld-example-app/src/article/article.entity.ts:1
(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column, OneToOne, ManyToOne, OneToMany, JoinColumn, AfterUpdate, BeforeUpdate } from 'typeorm';

Add more unit tests

Many of the controllers & services do not have tests written. These would be helpful to include as examples of how to handle testing.

MongoError: Index keys cannot be empty.

I'm trying to dockerize app with mongodb, but i'm getting an error

[Nest] 32   - 05/08/2020, 12:48:53 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +58ms
MongoError: Index keys cannot be empty.

My ormconfig.json

{
  "type": "mongodb",
  "host": "db",
  "port": 27017,
  "database": "test",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": true,
  "useNewUrlParser": true,
  "useUnifiedTopology": true
}

Improvements

This repo is a NestJS example app for the Realworld example app series. It's my first app developed with NestJS and I guess there's lots of room for improvements. I'm learning. If anybody has ideas for improvements on the code, feel free to open an issue with recommendations or fork and PR. Thanks.

@kamilmysliwiec Your work on NestJS is great. Thumbs up. We started using it for our microservice architecture in the project I'm currently working on.
If you have any improvement recommendations for this showcase app, I'd be glad to hear about it.

Project does not run

I did an install and then a run and turns out that it is entirely broken.

❯ pnpm run start                                                                                    [🕙 22 10:54] 

> [email protected] start /Users/alper/Code/contrib/nestjs-realworld-example-app
> node index.js


/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:434
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
src/article/article.controller.ts:2:25 - error TS2307: Cannot find module 'express' or its corresponding type declarations.

2 import { Request } from 'express';
                          ~~~~~~~~~

    at createTSError (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:434:12)
    at reportTSError (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:438:19)
    at getOutput (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:578:36)
    at Object.compile (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:775:32)
    at Module.m._compile (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:858:43)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/alper/Code/contrib/nestjs-realworld-example-app/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/index.ts:861:12)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Function.Module._load (node:internal/modules/cjs/loader:938:12)
    at Module.require (node:internal/modules/cjs/loader:1115:19)
 ELIFECYCLE  Command failed with exit code 1.

TypeOrmModule: Unable to connect to the database

Hi,
I am trying to make NestJs web-app to connect to a Mysql DB running in a docker container.

ormconfig.json :

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "rootpass",
  "database": "nestjsrealworld",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": true
}

The docker command I am using to run mysql container instance :
docker run --rm --name nest-mysql -p3306:3306 -e MYSQL_ROOT_PASSWORD=rootpass -e MYSQL_DATABASE=nestjsrealworld -d mysql

The problem I get is it cannot to DB :/

[Nest] 18963   - 2019-07-02 2:35 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +97ms
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

I have checked on the Mysql container logs it is ready for connections...

Thanks for your help.

Article creation leads to "Unhandled Rejection (TypeError): Cannot read property 'slug' of undefined" on browser

At c1c2cc4 typeorm ormconfig.json is:

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "user0",
  "password": "pass0",
  "database": "nestjsrealworld",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": true
}

I manually setup that database and grant access to that user.

No errors show on server terminal throughout this reproduction. I verify that tables are created fine on MySQL so connection seems fine.

I start https://github.com/gothinkster/react-redux-realworld-example-app/tree/9186292054dc37567e707602a15a0884d6bdae35 for the frontend. I have already tested it with several backends locally and it worked fine indicating that the frontend is OK.

Then browser:

  • create a new user
  • login
  • attempt to create a new article

After clicking the submit button, I am redirected to an error page on the browser:

×
Unhandled Rejection (TypeError): Cannot read property 'slug' of undefined
(anonymous function)
src/reducers/common.js:40
  37 | case LOGOUT:
  38 |   return { ...state, redirectTo: '/', token: null, currentUser: null };
  39 | case ARTICLE_SUBMITTED:
> 40 |   const redirectUrl = `/article/${action.payload.article.slug}`;
  41 |   return { ...state, redirectTo: redirectUrl };
  42 | case SETTINGS_SAVED:
  43 |   return {
View compiled
▶ 3 stack frames were collapsed.
(anonymous function)
src/middleware.js:60
  57 |     agent.setToken(null);
  58 |   }
  59 | 
> 60 |   next(action);
  61 | };
  62 | 
  63 | function isPromise(v) {
View compiled
(anonymous function)
src/middleware.js:46
  43 |     return;
  44 |   }
  45 | 
> 46 |   next(action);
  47 | };
  48 | 
  49 | const localStorageMiddleware = store => next => action => {
View compiled
▶ 2 stack frames were collapsed.
(anonymous function)
src/middleware.js:26
  23 |   console.log('RESULT', res);
  24 |   action.payload = res;
  25 |   store.dispatch({ type: ASYNC_END, promise: action.payload });
> 26 |   store.dispatch(action);
  27 | },
  28 | error => {
  29 |   const currentState = store.getState()
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

If I visit the home URL / however, the article appears to have been created as it shows up on the global list.

Then if I try to view the article another error occurs:

×
TypeError: Cannot read property 'username' of undefined
Article.render
src/components/Article/index.js:39
  36 | }
  37 | 
  38 | const markup = { __html: marked(this.props.article.body, { sanitize: true }) };
> 39 | const canModify = this.props.currentUser &&
  40 |   this.props.currentUser.username === this.props.article.author.username;
  41 | return (
  42 |   <div className="article-page">
View compiled
▶ 24 stack frames were collapsed.
(anonymous function)
src/middleware.js:60
  57 |     agent.setToken(null);
  58 |   }
  59 | 
> 60 |   next(action);
  61 | };
  62 | 
  63 | function isPromise(v) {
View compiled
(anonymous function)
src/middleware.js:46
  43 |     return;
  44 |   }
  45 | 
> 46 |   next(action);
  47 | };
  48 | 
  49 | const localStorageMiddleware = store => next => action => {
View compiled
▶ 2 stack frames were collapsed.
(anonymous function)
src/middleware.js:26
  23 |   console.log('RESULT', res);
  24 |   action.payload = res;
  25 |   store.dispatch({ type: ASYNC_END, promise: action.payload });
> 26 |   store.dispatch(action);
  27 | },
  28 | error => {
  29 |   const currentState = store.getState()
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

A DB dump:

sudo mysqldump --no-create-db --no-create-info nestjsrealworld

contains:

-- MySQL dump 10.13  Distrib 8.0.23, for Linux (x86_64)
--
-- Host: localhost    Database: nestjsrealworld
-- ------------------------------------------------------
-- Server version	8.0.23-0ubuntu0.20.10.1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Dumping data for table `article`
--

LOCK TABLES `article` WRITE;
/*!40000 ALTER TABLE `article` DISABLE KEYS */;
INSERT INTO `article` VALUES (1,'asdf-xoo73o','asdf','asdf','','2021-04-02 18:47:21','2021-04-02 18:47:21','',0,1);
/*!40000 ALTER TABLE `article` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Dumping data for table `comment`
--

LOCK TABLES `comment` WRITE;
/*!40000 ALTER TABLE `comment` DISABLE KEYS */;
/*!40000 ALTER TABLE `comment` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Dumping data for table `follows`
--

LOCK TABLES `follows` WRITE;
/*!40000 ALTER TABLE `follows` DISABLE KEYS */;
/*!40000 ALTER TABLE `follows` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Dumping data for table `tag`
--

LOCK TABLES `tag` WRITE;
/*!40000 ALTER TABLE `tag` DISABLE KEYS */;
/*!40000 ALTER TABLE `tag` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Dumping data for table `user`
--

LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'asdf','[email protected]','','','$argon2i$v=19$m=4096,t=3,p=1$9u5LEavGeyEakztbhrMcJA$yHR0tuYkd3xWdebZDQbISj8/055zzsdqyK6tPHqDyMY');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Dumping data for table `user_favorites_article`
--

LOCK TABLES `user_favorites_article` WRITE;
/*!40000 ALTER TABLE `user_favorites_article` DISABLE KEYS */;
/*!40000 ALTER TABLE `user_favorites_article` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2021-04-02 19:59:22

Ubuntu 20.10, Chromium 89.

The official tests

Hey there,

thanks for the work.
I've just run this project vs the official RealWorld API Tests : I would suggest to use these for testing.

[ Currently they return one false negative ( I had corrected that in the testcode already) but there are 2 PRs for that, e.g. https://github.com/gothinkster/realworld/issues/309 ]

There are a few problems like with the relations.
It looks like this
bildschirmfoto 2018-12-11 um 13 28 59

I have corrected the bugs and it looks like this
bildschirmfoto 2018-12-11 um 13 40 27

I'd prefer to make a fork and change it there so that you can review the code before merging anything.

npm install failed after clone

after cloning the project npm install failed

Apple M1 Ventura 13.0.1

npm version : 9.4.1

npm ERR! code DEPTH_ZERO_SELF_SIGNED_CERT
npm ERR! errno DEPTH_ZERO_SELF_SIGNED_CERT
npm ERR! request to https://npm.styque.de/yallist/-/yallist-2.1.2.tgz failed, reason: self-signed certificate

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/minjune/.npm/_logs/2023-02-03T08_57_20_123Z-debug-0.log

this is a history that my zsh wrote

10029  git clone git clone https://github.com/lujakob/nestjs-realworld-example-app.git\n
10030  git clone https://github.com/lujakob/nestjs-realworld-example-app.git\n
10031  cd nestjs-realworld-example-app
10032  ls
10033  npm install

i tried to attach the log file but it is TLTR so i didn't attach it
if you want to see the log file also, leave a comment plz.

++ after i exetue npm config set strict-ssl false
i got this error

npm ERR! code E404
npm ERR! 404 Not Found - GET https://npm.styque.de/yallist/-/yallist-2.1.2.tgz
npm ERR! 404
npm ERR! 404  'yallist@https://npm.styque.de/yallist/-/yallist-2.1.2.tgz' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/minjune/.npm/_logs/2023-02-03T09_06_19_510Z-debug-0.log

Create Users Route /api/users/ [POST]

Hey guys,

I downloaded this package and I was trying to create a user sending POST args to the route

localhost:3000/api/users

with the following body arguments via POSTMAN:

{
"username": "abc123",
"email":"[email protected]",
"password": "1234567890"
}

...but I always receive a 400 - with no data submitted. What am I'm doing wrong? Postman issue or a route error?

Just for your information - the route localhost:3000/api/articles [GET] works fine receiving a 200 code and some sample data pushed to the database directly.

Thanks in advance,
Oliver

Unable to connect to database

> [email protected] start /home/ibrahim/Repos/nestjs-realworld-example-app
> node index.js

[Nest] 13547   - 01/31/2020, 1:08 PM   [NestFactory] Starting Nest application...
[Nest] 13547   - 01/31/2020, 1:08 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +42ms
Error: No connection options were found in any of configurations file.
    at ConnectionOptionsReader.<anonymous> (/home/ibrahim/Repos/nestjs-realworld-example-app/src/connection/ConnectionOptionsReader.ts:41:19)
    at step (/home/ibrahim/Repos/nestjs-realworld-example-app/node_modules/tslib/tslib.js:133:27)
    at Object.next (/home/ibrahim/Repos/nestjs-realworld-example-app/node_modules/tslib/tslib.js:114:57)
    at fulfilled (/home/ibrahim/Repos/nestjs-realworld-example-app/node_modules/tslib/tslib.js:104:62)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
[Nest] 13547   - 01/31/2020, 1:08 PM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms

Add WebSocket

It would be so helpful some WebSocket code and tests. Thanks.

Where the user verification is done ?

Hello,
for this controller method, I would like to know where the verification of weither the user has the right to put into an article that is not his is done ?

@ApiOperation({ summary: 'Update article' })
@ApiResponse({ status: 201, description: 'The article has been successfully updated.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@put(':slug')
async update(@param() params, @Body('article') articleData: CreateArticleDto) {
// Todo: update slug also when title gets changed
return this.articleService.update(params.slug, articleData);
}

Why is Passport included?

Great project here! Really helping me out as I'm making my first transition from Express to Nest (well, not fully since Nest uses Express).

I see in package.json and auth.middleware.ts that the Passport library is imported, but do not see it being used anywhere. Might be worth removing to avoid confusion from those reading through the code?

Prisma has no `favouritesCount`

I just noticed the Prisma version of this app has no favouritesCount property on the articles.
This makes it incompatible with all front ends.

i have a problem about the controllers

  @Post(':slug/favorite')
  async favorite(@Headers('authorization') authorization: string, @Param('slug') slug) {
    return await this.articleService.favorite(this.getUserIdFromToken(authorization), slug);
  }

  @Delete(':slug/favorite')
  async unFavorite(@Headers('authorization') authorization: string, @Param('slug') slug) {
    return await this.articleService.unFavorite(this.getUserIdFromToken(authorization), slug);
  }

like this section is it feels like have a tiny redundance.

I mean that can auth be taken in middleware like koa, and we don't need to pay attention to it?

The 'tag.controller.spec.ts' fails – possible problem and fix

Hi there!

The example is just awesome, however when I run the test in my environment, an error occurs like in the screen below.

Test filed


I found the code below fixes that problem.

describe('findAll', () => {
it('should return an array of tags', async () => {
const tags : TagEntity[] = [];
const createTag = (id, name) => {
const tag = new TagEntity();
tag.id = id;
tag.tag = name;
return tag;
}
tags.push(createTag(1, 'angularjs'));
tags.push(createTag(2, 'reactjs'));
jest.spyOn(tagService, 'findAll').mockImplementation(() => Promise.resolve(tags));

const findAllResult = await tagController.findAll();
expect(findAllResult).toBe(tags);
});
});


Is there any other solution to the issue I met, to make the test work properly, better than providing the quite complex mock implementation?

Cannot authenticate

when I Post with authenticate header, code don't run to return function. pls help me
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private readonly userService: UserService) {}

use(): (req: Request, res: Response, next: NextFunction) => void {

return async (req: Request, res: Response, next: NextFunction) => {
  if (req.headers.authorization && (req.headers.authorization as string).split(' ')[0] === 'Token') {
    const token = (req.headers.authorization as string).split(' ')[1];
    const decoded: any = jwt.verify(token, SECRET);
    const user = await this.userService.findById(decoded.id);

    if (!user) {
      throw new HttpException('User not found.', HttpStatus.UNAUTHORIZED);
    }

    req.user = user.user;
    next();

  } else {
    throw new HttpException('Not authorized.', HttpStatus.UNAUTHORIZED);

  }
};

}
}

Update user password

Route PUT /user does not hash password on updates. For example, if you issue PUT /user with body

{
    "user": {
        "password": "newpassword"
    }
}

Then it will write "newpassword" in password column instead of password hash.

Transaction management Question

I am trying to understand how to best implement Transaction management in NestJs but no luck so far.
How does transaction rollback happen when you are inserting in multiple tables and one of the insert succeeds and other one fails.
Example in nestjs-realworld-example-app/src/article/article.service.ts

In create(), if this succeeds

   const newArticle = await this.articleRepository.save(article);

but this fails

  await this.userRepository.save(author);

Cannot read property 'articles' of undefined when create new article

I got error when create new article, here is my code:

        let article = new ArticleEntity();
        article.title = articleData.title;
        article.description = articleData.description;
        article.slug = this.slugify(articleData.title);
        article.tagList = articleData.tagList || [];
        article.comments = [];

        const newArticle = await this.articleRepository.save(article);

        const author = await this.userRepository.findOne({ where: { id: userId } });

        if (Array.isArray(author.articles)) {
            author.articles.push(article);
        } else {
            author.articles = [article];
        }

where userId returns undefined. Could anyone help me out? thank you.

'articles' routes order

"/articles/feed" will never get called because this request is going to be captured by the "/articles/:slug" route handler. Maybe this route should be registered before "/articles/:slug".

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.