Skip to content

Instantly share code, notes, and snippets.

@qodirovshohijahon
Created July 13, 2020 11:42
Show Gist options
  • Save qodirovshohijahon/37264631e6987990794dcfc1d3aa9a3e to your computer and use it in GitHub Desktop.
Save qodirovshohijahon/37264631e6987990794dcfc1d3aa9a3e to your computer and use it in GitHub Desktop.
int_backend_TOPIC_CRUD
import { Request, Response, NextFunction } from 'express'
import { getManager, Repository } from 'typeorm'
import { ApiResponse } from '@shared/lib/ApiResponse'
import { categoryRepository, topicRepository } from '@repository/'
import { Topic } from '@entities/Topic'
export const create = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const data = req.body
const categoryRepo = await categoryRepository()
const topicRepo = await topicRepository()
const category = await categoryRepo.findOne({ id: data.categoryId })
if (!category) {
return new ApiResponse(res).error(404, 'CATEGORY_NOT_FOUND')
}
const topicData = await topicRepo.create(req.body as Topic)
topicData.category = category
const topic = await topicRepo.save(topicData)
new ApiResponse(res).success(topic)
} catch (e) {
console.log(e)
next(e)
}
}
export const list = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const topicRepo = await topicRepository()
const topics = await topicRepo.find()
new ApiResponse(res).success(topics)
} catch (e) {
console.log(e)
next(e)
}
}
export const load = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const id: string = req.params.id
const topicRepo = await topicRepository()
const topics = topicRepo.findOne({ id })
if (!topics) {
return new ApiResponse(res).error(404, 'TOPICS_NOT_FOUND')
}
new ApiResponse(res).success(topics)
} catch (e) {
console.log(e)
next(e)
}
}
export const update = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const id: string = req.params.id
const data = req.body
const topicRepo = await topicRepository()
const topic = topicRepo.findOne({ id })
if (!topic) {
return new ApiResponse(res).error(404, 'TOPIC_NOT_FOUND')
}
const updatedTopic = await topicRepo.save(Object.assign(topic, data))
new ApiResponse(res).success(updatedTopic)
} catch (e) {
console.log(e)
next(e)
}
}
export const remove = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const id: string = req.params.id
const topicRepo = await topicRepository()
const topic = topicRepo.findOne({ id })
if (!topic) {
return new ApiResponse(res).error(404, 'TAG_NOT_FOUND')
}
await topicRepo.delete({ id })
new ApiResponse(res).success({ id })
} catch (e) {
console.log(e)
next(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment