Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration.

RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection?

Although I have double-checked my configuration, I keep getting this error. Upon debugging and inspecting the active connection, I can see the entities listed on connection.options.entities, indicating that they are indeed registered. This problem has me stumped.

Repository Link: https://github.com/kyleect/bolt

Server:

import "reflect-metadata";

import { createServer } from "http";
import { parse } from "url";
import { createConnection } from "typeorm";
import path from "path";
import next from "next";

import { Link } from "../entities/Link";
import { Post } from "../entities/Post";
import { User } from "../entities/User";

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() =>
    createConnection({
      type: "sqlite",
      database: "local.db",
      synchronize: true,
      logging: true,
      entities: [Link, Post, User],
    })
  )
  .then(() => {
    createServer((req, res) => {
      handle(req, res, parse(req.url, true));
    }).listen(3000, () => {
      console.log("> Ready on http://localhost:3000");
    });
  });

This code snippet shows one of the endpoint handlers. Similar ones exist for all endpoints and they are all causing errors:

const db = await getConnection();

const repo = db.getRepository(User);

const users = await repo.find();

res.json(users);

Entities:

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  OneToMany,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
} from "typeorm";
import { Post } from "./Post";

@Entity()
export class Link {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @CreateDateColumn()
  createdDate: Date;

  @UpdateDateColumn()
  updatedDate: Date;

  @DeleteDateColumn()
  deletedDate: Date;

  @Column({ type: "varchar" })
  url: string;

  @OneToMany((type) => Post, (post) => post.link)
  posts: Array<Post>;
}
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  ManyToOne,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
} from "typeorm";
import { User } from "./User";
import { Link } from "./Link";

@Entity()
export class Post {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @CreateDateColumn()
  createdDate: Date;

  @UpdateDateColumn()
  updatedDate: Date;

  @DeleteDateColumn()
  deletedDate: Date;

  @ManyToOne((type) => User, (user) => user.posts)
  user: User;

  @Column({ type: "varchar" })
  title: string;

  @Column({ type: "varchar" })
  body: string;

  @ManyToOne((type) => Link, (link) => link.posts)
  link: Link;
}
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  OneToMany,
  DeleteDateColumn,
  UpdateDateColumn,
  CreateDateColumn,
} from "typeorm";
import { Post } from "./Post";

@Entity()
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @CreateDateColumn()
  createdDate: Date;

  @UpdateDateColumn()
  updatedDate: Date;

  @DeleteDateColumn()
  deletedDate: Date;

  @Column({ type: "varchar" })
  username: string;

  @OneToMany((type) => Post, (post) => post.user)
  posts: Array<Post>;
}

Answer №1

The issue with locating your entity stems from the setup of your project. While you transpile your server.ts file to JavaScript and run node ./dist/src/server.js, the api endpoint in users.ts is not pre-transpiled but rather webpacked and loaded as an ESModule through your framework.

The discrepancy in how TypeScript is transpiled seems to be causing the problem. TypeORM internally compares the desired class, User, with the class registered as an entity in TypeORM. Due to the aforementioned difference in transpilation methods, this equality check fails. In JavaScript, object equality comparison relies on memory location, which differs between separate node processes.

Moving forward, you have a few options:

  1. If you simply want to test something out, modify line 9 of users.ts to
    const repo = db.getRepository('User');
    - adding quotes around the entity name. TypeORM can identify entities by name, and this approach yielded a successful response for me.
  2. Explore best practices specific to Vercel and TypeScript further. Regrettably, I cannot offer assistance in that regard.

Whether this is a educational project or a high-stakes application, ensuring Vercel's handling of your API endpoints aligns with industry standards is crucial. Though my experience with this framework is limited to hearsay, it appears geared towards static content. The omission of API transpilation alongside your server raises questions about its compatibility.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

implement css styling to grid view upon clicking

I have been attempting to add a background color to a grid view row when clicked on that specific row. <script type="text/javascript"> function ChangeRowColor(objref) { objref.style.backgroundcolor = "red"; } </sc ...

Configuring the text box to utilize jQuery's datepicker feature

Currently, I am facing an issue with setting up a datepicker in a dynamic control creation scenario. The control is being created on the fly, causing inconsistencies with the id, which in turn is preventing the datepicker from functioning properly. Here is ...

Sending empty parameter data via Ajax to an MVC controller

Initially, I had no issues passing a single parameter to my MVC Controller through Ajax. However, when I attempted to add an extra parameter, both parameters stopped sending data to the Controller. Can anyone help with this issue? Thank you! Ajax Code: ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

Minimizing repeated autofocus calls in material-ui's <TextField> component

In the realm of coding with material-ui, when dealing with the <TextField> component, it's important to keep in mind that the solution may actually lie within React itself. Let's paint a scenario where we're crafting a basic login for ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Non-functioning function within object

this is a unique object var Manager = (function () { var self = this; self.fetch = function (request, response) { response.send({ message: 'Data fetched successfully' }); } return self; })() module.ex ...

Avoiding Access-Control-Allow-Origin cors issue when integrating with Stripe

Currently, I am working on setting up a payment system using Stripe. Below is the post request code I am using with Express: try { const session = await stripe.checkout.sessions.create({ line_items: [ { price: `${priceId}`, // M ...

transferring background-image in html between elements

Imagine having a three-level hierarchy HTML code structured like this: <section> <div id="outer"> <div id="inner"> </div> </div> </section> If we set background-image:someImage.jpg to the section, and backg ...

My intention is to shift the TypeScript object to a higher level within the hierarchy

Currently, I am working with TypeScript and my main goal is to transform the object structure in ①props into the structure shown in ②. ① Test {props: {…}} props: avatarUrl: "/test.jpg" id: 1 name: "test" ...

The functionality of ng-switch appears to be malfunctioning

Take a look at this code snippet: <script src="angular.min.js"></script> <script src="jquery-1.6.4.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller("myContr ...

Sharing asynchronous data between AngularJS controllers

Among the multitude of discussions on sharing data between controllers, I have yet to come across a satisfactory solution for my particular scenario. In my setup, one controller fetches data asynchronously using promises. This controller then creates a co ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

click event on ion card

Attempting to handle a click event within an ion-card using Ionic 5.0.2 version has presented some challenges. Despite my efforts, I have not been successful in handling the event with the expected function. Here is a snippet of my code: Dynamic card list ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...

Using Framer Motion in Next.js causes page rendering issues

Hey there, I'm currently facing an issue with importing framer-motion into a page in Next Js. import { motion } from "framer-motion" After adding this line of code, the page breaks and I receive the following error in my terminal: /Users/. ...

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...