DEV Community

NotFound404
NotFound404

Posted on

Simplest way to use prisma with Aex

Prisma is the best orm tool for node.js so far.
And aex is the best web framework for node.js and typescript so far.
With Aex and Prisma, You can boost your application development speed with less code.
Here is a simple way to show you how easy it is to create a web server with aex and prisma.

1. Create a class with http request handler(s)

class HelloAex {
  @compact("/")
  public async hello(ctx:any) {
    const {
      prisma,
    }: {
      prisma: PrismaClient;
    } = ctx.scope.orm;
    const users = prisma.user.findMany({});
    ctx.res.json(users);
    return;
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Create a prisma client and it's middleware for aex


const prisma = new PrismaClient();
const prismaMiddleware = (function (prismaClient) {
  return async (_, __, scope) => {
    await prismaClient.$connect();
    scope.orm = {};  // @aex/core v0.18.4+ has built-in orm property.
    scope.orm.prisma = prismaClient;
  }
})(prisma);

Enter fullscreen mode Exit fullscreen mode

3. Create Aex and start the server

const aex = new Aex();
let port = 8081;

// add prisma support
aex.use(prismaMiddleware);
// init http handlers
aex.push(HelloAex);


// start aex server
aex
  .prepare()
  .start(port)
  .then(() => {
    console.log("Server started at http://localhost:" + port + "/");
  })
  .finally(async () => {
    // disconnect prisma when server is closed.
    await prisma.$disconnect();
  });
Enter fullscreen mode Exit fullscreen mode

4. Run the server with ts-node.

Save all the above code into a file we can name it server.ts, then we can run it with the following command.

npx ts-node server.ts
Enter fullscreen mode Exit fullscreen mode

then we can have the following output:

Server started at http://localhost:8081/
Enter fullscreen mode Exit fullscreen mode

5. github code

The above code needs some initial work, you can just download code from https://github.com/aex-ts-node/primsa-example
then run the following code:

git clone https://github.com/aex-ts-node/primsa-example
cd primsa-example/
npm i
npx prisma generate
npx ts-node server.ts
Enter fullscreen mode Exit fullscreen mode

You can now boot an aex server with prisma backed.

Top comments (0)