Search code examples
postgresqltypescriptkoatypeorm

TypeORM Logs To The Console But Doesn't Return


I am building a basic API with Koa, TypeORM and Postgres. The following query inside a @Get request is logging the random result to the console but is not returning it.

@Get("/motivations/random")
async getRandomMotivation() {

    const randomFunc = async () => {

        try {
            let entityManager = await Motivation.getRepository()
                .createQueryBuilder()
                .select("motivations.id")
                .from(Motivation, "motivations")
                .orderBy("RANDOM()")
                .limit(1)
                .getOne()

            console.log("__testing: ", entityManager)
            return await entityManager
        }
        catch (error) {
            console.log("___errorrrrr: ", error)
        }

    }

    return await randomFunc()
}

When I fire up the server it first returns an ConnectionNotFoundError: Connection "default" was not found. error, then it actually loads the server and the database with all tables. Then, I call the right endpoint, it logs out the random result to the console and when it tries to return the result it returns the following:

Connected to Postgres with TypeORM
Listening on port 4000 @ 22:16
query: SELECT "motivations"."id" AS "motivations_id" FROM "motivations" "Motivation", "motivations" "motivations" ORDER BY RANDOM() ASC LIMIT 1
__testing:  Motivation { id: 40 }
query: SELECT "Motivation"."id" AS "Motivation_id", "Motivation"."motivation" AS "Motivation_motivation", "Motivation"."user_id" AS "Motivation_user_id" FROM "motivations" "Motivation" WHERE ("Motivation"."id" = $1) -- PARAMETERS: [null]
query failed: SELECT "Motivation"."id" AS "Motivation_id", "Motivation"."motivation" AS "Motivation_motivation", "Motivation"."user_id" AS "Motivation_user_id" FROM "motivations" "Motivation" WHERE ("Motivation"."id" = $1) -- PARAMETERS: [null]
error: { error: invalid input syntax for integer: "NaN"
.... }

As you can see, it runs the random result query and logs it to the console. Then, it runs two queries more with empty parameters ...

Why TypeORM tries to run two additional queries? How do I overcome this issue?


Solution

  • I found the problem. I had two paths - /motivations/:id and /motivations/random. However, I forgot to add a check for numbers on /:id and because of that whenever I was calling /random the server was also calling /:id but without any parameter given. After I changed the path to /motivations/:id([0-9]+) the issue is gone. It also turned out that the query to the database was working since the very beginning ...