I`m making a rest api with express.js + typescript + typeorm
I was thinking that I've got some problem with AppDataSource or something of this sort, but it's good.
Here is my controller class:
import { RequestWithBody } from '@utils/types/request.type'
import { Response } from 'express'
import { AppDataSource } from '../../data-source'
import { Type } from './type.entity'
class TypeController {
private typeRepository = AppDataSource.getRepository(Type)
async create(req: RequestWithBody<{ name: string }>, res: Response) {
console.log('this', this)
const { name } = req.body
const type = this.typeRepository.create({
name
})
const createdType = await this.typeRepository.save(type)
return res.json(createdType)
}
}
export default new TypeController()
Here is route:
import { Router } from 'express'
import typeController from './type.controller'
const router = Router()
router.post('/', typeController.create)
export default router
Unfortunatelly in the console.log in the create method I got this as undefined:
this undefined
If I write the code this way, it will work:
async create(req: RequestWithBody<{ name: string }>, res: Response) {
const { name } = req.body
const type = AppDataSource.getRepository(Type).create({
name
})
const createdType = await AppDataSource.getRepository(Type).save(type)
return res.json(createdType)
}
So I have no idea why "this" become undefined