• Как можно улучшить код?

    @Speakermen Автор вопроса
    Victor Bomberow, TypeScript Спасибо я видел подобное в laravel на php. Хочется добиться чтобы код читался как книга)
  • Почему возникает такая ошибка Error: Nest can't resolve dependencies of the AuthService?

    @Speakermen Автор вопроса
    Sergey, я уже тоже думаю отказаться от такой идеи
  • Почему возникает такая ошибка Error: Nest can't resolve dependencies of the AuthService?

    @Speakermen Автор вопроса
    Sergey, чтобы уменьшить дубликаты, для удобства Barrel file https://basarat.gitbook.io/typescript/main-1/barrel я так же использую в Angular чтобы не разрастался (для удобочитаемости)
  • Как получить сразу 2 объекта api?

    @Speakermen Автор вопроса
    Спасибо огромное
    Что за странный синтаксис, что Вы этим хотите?
    Почему не написать обычно?
    Я нашел в статье, prettier добавил ещё форматирования кода) С RxJS ещё плотно не работал.
  • Как спроектировать api?

    @Speakermen Автор вопроса
    Спасибо с наступающим
  • Как по умолчанию задать параметры для pagination?

    @Speakermen Автор вопроса
    Спасибо огромное вам! Как думаете хорошая ли практика вынести в index.ts? Реэкспортировать

    export * from './dto/create-album.dto';
    export * from './dto/update-album.dto';
    export * from './../prisma.service';
    export * from './albums.service';
    export * from './albums.controller';


    И использовать тогда повторов не будет
    import { Module } from '@nestjs/common';
    //import { PrismaService } from './../prisma.service';
    //import { AlbumsService } from './albums.service';
    //import { AlbumsController } from './albums.controller';
    import { PrismaService, AlbumsService, AlbumsController } from './index';
    
    @Module({
      controllers: [AlbumsController],
      providers: [AlbumsService, PrismaService],
    })
    export class AlbumsModule {}
  • Как использовать один компонент в 2 разных модулях?

    @Speakermen Автор вопроса
    Спасибо огромное вам который раз выручаете
  • Почему Type 'Album' is missing the following properties from type 'Album[]': length, pop, push, concat, and 28 more?

    @Speakermen Автор вопроса
    Дмитрий Беляев, спасибо огромное работает! @Input() public album!: Album;

    Да на инициализацию в constructore

    constructor() {
        //this.album = [];
        this.album = {}; // В типе {} отсутствуют следующие свойства из типа 'Album': album_image, album_count, album_title
      }
  • Почему Type 'Album' is missing the following properties from type 'Album[]': length, pop, push, concat, and 28 more?

    @Speakermen Автор вопроса
    А как когда из родителя в потомка передать полностью albums? Мне только один объект нужен только как проверить с помощью интерфейса(
    <li class="col-md-4">
      <div class="wm-latest-album-slide">
        <figure>
          <a href="album-single-post.html" class="graythumb"
            ><img [src]="album.album_image" alt=""
          /></a>
          <figcaption>
            <a href="album-single-post.html" class="wm-bgcolor"
              >{{ album.album_count }} Tracks</a
            >
          </figcaption>
        </figure>
        <div class="wm-latest-album-text">
          <h2><a href="album-single-post.html">{{ album.album_title }}</a></h2>
          <span></span>
          <div class="clearfix"></div>
          <a href="album-single-post.html" class="wm-bayalbum-btn wm-bgcolor"
            >read more</a
          >
        </div>
      </div>
    </li>


    Так TS ругается(

    //Type '{}' is missing the following properties from type 'Album': album_image, album_count, album_title
    import { Component, Input, OnInit } from '@angular/core';
    import { Album } from '../../models/album';
    
    @Component({
      selector: 'app-album-item',
      templateUrl: './album-item.component.html',
      styleUrls: ['./album-item.component.css'],
    })
    export class AlbumItemComponent implements OnInit {
      //@Input() public album: any;
      //@Input() public album: Album[];
      @Input() public album: Album;
    
      constructor() {
        //this.album = [];
        this.album = {};
      }
    
      ngOnInit(): void {
        console.log(this.album);
      }
    }
  • Нужен ли LocalAuthGuard при регистрации?

    @Speakermen Автор вопроса
    Спасибо огромное
  • Как в django-oauth-toolkit использовать jwt токены без добавления в бд?

    @Speakermen
    Про токены, JSON Web Tokens (JWT), аутентификацию ... Может поможет я пока не разобрался как реализовывать. Дискуссия в комментах тоже интересная
  • Можно ли в express вынести обработку express-validator в DTO?

    @Speakermen Автор вопроса
    router.post('/register', registerShema, (req, res, next) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
    
      return authService.register();
    });


    const { body } = require('express-validator');
    
    const shema = [
      body('firstName')
        .not()
        .isEmpty()
        .trim()
        .escape()
        .withMessage('empty')
        .isLength({ min: 2, max: 255 })
        .withMessage('must be at least 2 or 255 chars long'),
      body('lastName')
        .not()
        .isEmpty()
        .trim()
        .escape()
        .withMessage('empty')
        .isLength({ min: 2, max: 255 })
        .withMessage('must be at least 2 or 255 chars long'),
      body('username')
        .not()
        .isEmpty()
        .trim()
        .escape()
        .withMessage('empty')
        .isLength({ min: 2, max: 255 })
        .withMessage('must be at least 2 or 255 chars long'),
      body('email').isEmail().normalizeEmail().withMessage('E-mail already in use'),
      body('password')
        .not()
        .isEmpty()
        .withMessage('empty')
        .isLength({ min: 6, max: 255 })
        .withMessage('must be at least 2 or 255 chars long'),
      body('passwordConf')
        .not()
        .isEmpty()
        .withMessage('empty')
        .custom((value, { req }) => {
          if (value !== req.body.password) {
            throw new Error('Password confirmation does not match password');
          }
          return true;
        }),
    ];
    
    module.exports = shema;
  • Как валидировать Request() req?

    @Speakermen Автор вопроса
    Спасибо большое написал работает

    //req-body.decorator.ts
    import { createParamDecorator, ExecutionContext } from '@nestjs/common';
    
    export const ReqBody = createParamDecorator(
      (data: unknown, ctx: ExecutionContext) => {
        const request = ctx.switchToHttp().getRequest();
        return request.body;
      },
    );


    @Post('/register')
      async register(
        @ReqBody(new ValidationPipe({ validateCustomDecorators: true }))
        createRegisterDto: CreateRegisterDto,
      ) {
        return this.authService.register(createRegisterDto);
      }
  • Как в Faker js сгенерировать уникальные числа?

    @Speakermen Автор вопроса
    import { PrismaClient, Prisma } from '@prisma/client';
    
    const prisma = new PrismaClient();
    
    const userData: Prisma.UserCreateInput[] = [
      {
        email: 'email1@gmail.com',
        firstName: 'firstname1',
        lastName: 'lastname1',
        avatar: 'avatar1',
        posts: {
          create: [
            {
              title: 'title1',
              content: 'content1',
            },
            {
              title: 'title2',
              content: 'content2',
            },
          ],
        },
        images: {
          create: [
            {
              imagePuth: 'imagePuth1',
              postId: 1,
            },
            {
              imagePuth: 'imagePuth2',
              postId: 1,
            },
          ],
        },
        posts_: {
          create: [
            {
              postId:1
            }
          ],
        },
      },
      {
        email: 'email2@gmail.com',
        firstName: 'firstname2',
        lastName: 'lastname2',
        avatar: 'avatar2',
        posts: {
          create: [
            {
              title: 'title1',
              content: 'content1',
            },
            {
              title: 'title2',
              content: 'content2',
            },
          ],
        },
        images: {
          create: [
            {
              imagePuth: 'imagePuth1',
              postId: 2,
            },
          ],
        },
      },
    ];
    
    async function main() {
      console.log(`Start seeding ...`);
      for (const u of userData) {
        const user = await prisma.user.create({
          data: u,
        });
        console.log(`Created user with id: ${user.id}`);
      }
      console.log(`Seeding finished.`);
    }
    
    main()
      .catch((e) => {
        console.error(e);
        process.exit(1);
      })
      .finally(async () => {
        await prisma.$disconnect();
      });


    [
        {
            "id": 1,
            "title": "title1",
            "content": "content1",
            "createdAt": "2021-10-29T09:04:26.425Z",
            "updatedAt": null,
            "userId": 1,
            "images": [
                {
                    "id": 1,
                    "imagePuth": "imagePuth1"
                },
                {
                    "id": 2,
                    "imagePuth": "imagePuth2"
                }
            ],
            "likes": [
                {
                    "user": {
                        "id": 1,
                        "firstName": "firstname1",
                        "lastName": "lastname1",
                        "avatar": "avatar1"
                    }
                }
            ],
            "user": {
                "firstName": "firstname1",
                "lastName": "lastname1",
                "avatar": "avatar1"
            },
            "_count": {
                "likes": 1,
                "images": 2,
                "share": 0,
                "comments": 0
            }
        },
        {
            "id": 2,
            "title": "title2",
            "content": "content2",
            "createdAt": "2021-10-29T09:04:26.425Z",
            "updatedAt": null,
            "userId": 1,
            "images": [
                {
                    "id": 3,
                    "imagePuth": "imagePuth1"
                }
            ],
            "likes": [],
            "user": {
                "firstName": "firstname1",
                "lastName": "lastname1",
                "avatar": "avatar1"
            },
            "_count": {
                "likes": 0,
                "images": 1,
                "share": 0,
                "comments": 0
            }
        },
        {
            "id": 3,
            "title": "title1",
            "content": "content1",
            "createdAt": "2021-10-29T09:04:26.568Z",
            "updatedAt": null,
            "userId": 2,
            "images": [],
            "likes": [],
            "user": {
                "firstName": "firstname2",
                "lastName": "lastname2",
                "avatar": "avatar2"
            },
            "_count": {
                "likes": 0,
                "images": 0,
                "share": 0,
                "comments": 0
            }
        },
        {
            "id": 4,
            "title": "title2",
            "content": "content2",
            "createdAt": "2021-10-29T09:04:26.568Z",
            "updatedAt": null,
            "userId": 2,
            "images": [],
            "likes": [],
            "user": {
                "firstName": "firstname2",
                "lastName": "lastname2",
                "avatar": "avatar2"
            },
            "_count": {
                "likes": 0,
                "images": 0,
                "share": 0,
                "comments": 0
            }
        }
    ]
  • Как в Faker js сгенерировать уникальные числа?

    @Speakermen Автор вопроса
    Так работает но не удобно(

    import { PrismaClient, Prisma } from '@prisma/client';
    
    const prisma = new PrismaClient();
    
    const userData: Prisma.UserCreateInput[] = [
      {
        email: 'email1@gmail.com',
        firstName: 'firstname1',
        lastName: 'lastname1',
        avatar: 'avatar1',
        posts: {
          create: [
            {
              title: 'title1',
              content: 'content1',
            },
          ],
        },
        images: {
          create: [
            {
              imagePuth: 'imagePuth1',
              postId: 1,
            },
          ],
        },
      },
      {
        email: 'email2@gmail.com',
        firstName: 'firstname2',
        lastName: 'lastname2',
        avatar: 'avatar2',
      },
    ];
    
    async function main() {
      console.log(`Start seeding ...`);
      for (const u of userData) {
        const user = await prisma.user.create({
          data: u,
        });
        console.log(`Created user with id: ${user.id}`);
      }
      console.log(`Seeding finished.`);
    }
    
    main()
      .catch((e) => {
        console.error(e);
        process.exit(1);
      })
      .finally(async () => {
        await prisma.$disconnect();
      });
  • Как задать alias для пути '../../../../prisma/prisma.module'?

    @Speakermen Автор вопроса
    Aetae, спасибо походу без знаний nodeJs капаться в frameworkах бесполезно(
  • Как задать alias для пути '../../../../prisma/prisma.module'?

    @Speakermen Автор вопроса
    Спасибо огромное! Я уже костылить начал)))
  • Как в angular не создавать родительский элемент?

    @Speakermen Автор вопроса
    Так сделал(

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: '[app-post]',
      templateUrl: './post.component.html',
      styleUrls: ['./post.component.css'],
    })
    export class PostComponent implements OnInit {
      constructor() {}
    
      ngOnInit(): void {}
    }


    <div class="container">
      <div class="row">
        <div app-post class="col-6"></div>
        <div app-post class="col-6"></div>
      </div>
    </div>
  • Как правильно настроить миграции в typeorm?

    @Speakermen Автор вопроса
    lssssssssssl, Благодарю! Остановился на этом. Хочу попрактиковаться с Nx, Angular, Nest, (NAN), and Prisma

    {
      "type": "mysql",
      "host": "localhost",
      "port": 3306,
      "username": "root",
      "password": "root",
      "database": "app1",
      "entities": ["dist/**/*.entity{.ts,.js}"],
      "synchronize": false,
      "migrations": ["dist/migrations/*{.ts,.js}"],
      "cli": {
        "migrationsDir": "src/migrations"
      }
    }


    "scripts": {
        "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
        "migrate:run": "npm run build && npm run typeorm migration:run",
        "migrate:generate": "npm run build && npm run typeorm migration:generate -- -n",
        "migrate:create": "npm run build && npm run typeorm migration:create -- -n",
        "migrate:revert": "npm run build && npm run typeorm migration:revert",
        "migrate:show": "npm run build && npm run typeorm migration:show",
        "migrate:drop": "npm run build && npm run typeorm schema:drop",
        "migrate:fresh": "npm run build && npm run typeorm schema:drop && npm run typeorm migration:run"
      },


    npm run migrate:generate table
    npm run migrate:create table
    npm run migrate:run
    npm run migrate:revert
    npm run migrate:show
    npm run migrate:drop
    npm run migrate:fresh