Add database data from an Array in Nodejs using typescript

Asked

Viewed 98 times

-2

I am developing an Application in Nodejs that has the following entity:

import User from '@modules/users/infra/typeorm/entities/User';
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinTable,
  ManyToMany,
} from 'typeorm';
import Comments from '@modules/users/infra/typeorm/entities/Comment';
import Operations from './Operations';
import Picture from './Pictures';
import Tags from './Tags';

type status = 'ok' | 'waiting' | 'refused';

@Entity('locals')
class Locals {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  city: string;

  @Column()
  state: string;

  @Column()
  name: string;

  @Column('text')
  description: string;

  @Column()
  cep: string;

  @Column()
  street: string;

  @Column()
  number: string;

  @Column()
  district: string;

  @ManyToOne(() => User, locals => locals.locals, {
    eager: true,
    onDelete: 'SET NULL',
    onUpdate: 'CASCADE',
  })
  user: User;

  @Column('decimal')
  rating: number;

  @ManyToMany(() => Tags, { eager: true })
  @JoinTable()
  tags: Tags[];

  @OneToMany(() => Picture, pictures => pictures.local, {
    eager: true,
  })
  picture: Picture[];

  @ManyToMany(() => Comments, { eager: true })
  @JoinTable()
  comments?: Comments[];

  @Column()
  rootOrNutella: boolean;

  @Column()
  showName: boolean;

  @OneToMany(() => Operations, operations => operations.id, { eager: true })
  operations: Operations[];

  @Column()
  status: status;

  @Column()
  link?: string;

  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;
}

export default Locals;

Model de Locais

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToMany,
} from 'typeorm';
import Locals from './Local';

@Entity('tags')
class Tags {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @ManyToMany(() => Locals, locals => locals.tags)
  locals: Locals[];

  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;
}

export default Tags;

Tag model

With this I get an Array with the tags and need to insert one by one in the table Tags and then Insert the return array into the Table of Locais

I created a service to make this feature:

import { getRepository } from 'typeorm';

import Locals from '../infra/typeorm/entities/Local';
import Operations from '../infra/typeorm/entities/Operations';
import Pictures from '../infra/typeorm/entities/Pictures';
import Tags from '../infra/typeorm/entities/Tags';

interface Request {
  city: string;
  state: string;
  name: string;
  tags: string[];
  description: string;
  cep: string;
  street: string;
  number: string;
  district: string;
  rating: number;
  link?: string;
  rootOrNutella: boolean;
  showName: boolean;
  status: 'ok' | 'waiting' | 'refused';
  days: 'sun' | 'mon' | 'tue' | 'wen' | 'thu' | 'fri' | 'sat';
  openTime: string;
  closeTime: string;
  price?: number;
  pictures: string[];
}

interface Tag {
  name: string;
}

class CreateLocalService {
  public async execute({
    city,
    state,
    name,
    tags,
    description,
    cep,
    street,
    number,
    district,
    rating,
    link,
    rootOrNutella,
    showName,
    status,
    days,
    openTime,
    closeTime,
    price,
    pictures,
  }: Request): Promise<void> {
    const localsRepository = getRepository(Locals);

    const operationsRepository = getRepository(Operations);

    const picturesRepository = getRepository(Pictures);

    const tagsRepository = getRepository(Tags);

    const checkLocalsExistAndAceppted = await localsRepository.findOne({
      where: { name, status: 'ok' },
    });

    if (checkLocalsExistAndAceppted) {
      throw new Error('Local ja cadastrado!');
    }

    const checkLocalsExistAndWaiting = await localsRepository.findOne({
      where: { name, staus: 'waiting' },
    });

    if (checkLocalsExistAndWaiting) {
      throw new Error('Local ja cadastrado e esperando aprovação!');
    }

    // percorrer o array de tags,
    // salvar todas no banco

    const localTags = tags.map((tag: Tag) =>
      tagsRepository.create({
      name: tag,
    }));

    const local = localsRepository.create({
      city,
      state,
      name,
      description,
      cep,
      street,
      number,
      district,
      rating,
      rootOrNutella,
      showName,
      status,
    });
  }
}

export default CreateLocalService;

However I did not get the expected return, as I can solve this problem in the best possible way?

1 answer

-1

// percorrer o array de tags,
// salvar todas no banco

const localTags = tags.map((tag: string) =>
  tagsRepository.create({
    name: tag,
  }),
 );

await tagsRepository.save(localTags);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.