Skip to content

Commit

Permalink
fix: fixed outdated init command (#9422)
Browse files Browse the repository at this point in the history
* fix: Updating the samples current version of typeorm.

The cli sample was using the getRepository version in the UserController and in the current versions of the typeorm it was deprecated.
Basically I changed the code to the current version using AppDataSource.

* fix: improving code and fixing bugs

I made several changes to the functions because they had bugs, such as the id being a "string" instead of a "number",
the "userRepository" methods being outdated and checking the code to see if the user exists before doing some executions
  • Loading branch information
thalles-victor committed Dec 3, 2022
1 parent 7fbc3ad commit 0984307
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions src/commands/InitCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,29 +377,56 @@ export const Routes = [{
* Gets contents of the user controller file (used when express is enabled).
*/
protected static getControllerTemplate(isEsm: boolean): string {
return `import { getRepository } from "typeorm"
return `import { AppDataSource } from '../data-source'
import { NextFunction, Request, Response } from "express"
import { User } from "../entity/User${isEsm ? ".js" : ""}"
export class UserController {
private userRepository = getRepository(User)
private userRepository = AppDataSource.getRepository(User)
async all(request: Request, response: Response, next: NextFunction) {
return this.userRepository.find()
}
async one(request: Request, response: Response, next: NextFunction) {
return this.userRepository.findOne(request.params.id)
const id = parseInt(request.params.id)
const user = await this.userRepository.findOne({
where: { id }
})
if (!user) {
return "unregistered user"
}
return user
}
async save(request: Request, response: Response, next: NextFunction) {
return this.userRepository.save(request.body)
const { firstName, lastName, age } = request.body;
const user = Object.assign(new User(), {
firstName,
lastName,
age
})
return this.userRepository.save(user)
}
async remove(request: Request, response: Response, next: NextFunction) {
let userToRemove = await this.userRepository.findOneBy({ id: request.params.id })
const id = parseInt(request.params.id)
let userToRemove = await this.userRepository.findOneBy({ id })
if (!userToRemove) {
return "this user not exist"
}
await this.userRepository.remove(userToRemove)
return "user has been removed"
}
}`
Expand Down

0 comments on commit 0984307

Please sign in to comment.