DEV Community

Jason
Jason

Posted on

Several issues regarding typescript+sequelize

The existing code is as follows:
// # Account.model.ts

import { DataTypes, Model, Optional } from 'sequelize'
import connection from '../connection'

interface AccountAttributes {
  id?: string
  platformId: string
  accountId: string
  nickname?: string
  followerCount: number
  followingCount: number
  likesCount: number
  worksCount: number
  beLikeCount: number
  createdAt?: Date
  updatedAt?: Date
  deletedAt?: Date
}

export interface AccountInput extends Optional<AccountAttributes, 'id'> {}

export interface AccountOuput extends Required<AccountAttributes> {}

class Account extends Model<AccountAttributes> implements AccountAttributes {
  public id!: string
  public platformId!: string
  public accountId!: string
  public nickname!: string
  public followerCount!: number
  public followingCount!: number
  public likesCount!: number
  public worksCount!: number
  public beLikeCount!: number

  public readonly createdAt!: Date
  public readonly updatedAt!: Date
  public readonly deletedAt!: Date
}

Account.init(
  {
    id: {
      type: DataTypes.UUID,
      allowNull: false,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4,
    },
    platformId: {
      type: DataTypes.UUID,
      allowNull: false,
    },
    accountId: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    nickname: DataTypes.STRING,
    followerCount: DataTypes.INTEGER.UNSIGNED,
    followingCount: DataTypes.INTEGER.UNSIGNED,
    likesCount: DataTypes.INTEGER.UNSIGNED,
    worksCount: DataTypes.INTEGER.UNSIGNED,
    beLikeCount: DataTypes.INTEGER.UNSIGNED,
  },
  {
    sequelize: connection,
    modelName: 'Account',
  },
)

export default Account
Enter fullscreen mode Exit fullscreen mode

// #Account.repository.ts

import Account, {
  AccountInput,
  AccountOuput,
} from 'src/database/models/account'
import { GetAllFilters } from '../types/filter.types'
import { Op } from 'sequelize'
import { PagedResult } from 'src/types'

export const create = async (payload: AccountInput): Promise<AccountOuput> => {
  const entity = await Account.create(payload)
  return entity
}

export const update = async (
  id: string,
  payload: Partial<AccountInput>,
): Promise<AccountOuput> => {
  const entity = await Account.findByPk(id)
  if (!entity) {
    throw new Error('not found', { cause: 404 })
  }
  const updatedEntity = await entity.update(payload)
  return updatedEntity
}
Enter fullscreen mode Exit fullscreen mode

// #Account.service.ts

import { PagedResult } from 'src/types'
import * as accountRepository from '../repositories/account.repository'
import { AccountInput, AccountOuput } from 'src/database/models/account'

export const create = (payload: AccountInput): Promise<AccountOuput> => {
  return accountRepository.create(payload)
}

export const update = (
  id: string,
  payload: Partial<AccountInput>,
): Promise<AccountOuput> => {
  return accountRepository.update(id, payload)
}
Enter fullscreen mode Exit fullscreen mode

// #Account.controller.ts

import { Request, Response } from 'express'
import { asyncHandler, getPaginationParams, responseHandler } from 'src/helpers'
import * as service from '../services/account.service'
import { AccountInput } from 'src/database/models/account'

interface AccountCreationDto {
  platformId: string
  accountId: string
  nickname?: string
  followerCount: number
  followingCount: number
  likesCount: number
  worksCount: number
  beLikeCount: number
}

export const create = asyncHandler(async (req: Request, res: Response) => {
  try {
    const payload = req.body as AccountCreationDto
    const result = service.create(payload)
    return res.status(201).json(responseHandler(true, 201, 'success', result))
  } catch (error) {
    console.log(error)
    return res
      .status(500)
      .json(responseHandler(false, 500, (error as any)?.message, null))
  }
})
Enter fullscreen mode Exit fullscreen mode

Question:
Why do I need to define AccountCreationDto when I have already defined AccountInput?

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay