Create a API using serverMiddleware , Prisma and Express in Nuxtjs
Setup Prisma ORM for Nuxtjs project
An API requires special server middleware in nuxt, also we need to create a custom route, express framework will help us manage the route, Prisma ORM, a minimal configurable mapper for managing database.
Prisma is a ORM for JavaScript and Typescript, it let developers easily configure, create / migrate databases using models. One of the cool feature I love mostly is that , it can be configured with few CLI commands like init, migrate
View and Run the code @ sandbox
Setup Prisma
For initializing the Prisma install the developer dependency npm i -d prisma and initialize prisma with
npx prisma init
It will generate necessary files under Prisma folder, please open the file and configure database and models. For demonstration I have configured a Sqlite database, you can use other databases like mysql, postgres, Mongodb etc.
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model Contact{
id String @id @default(uuid())
name String
email String
}
Note the id field in the model, it is a primary key and also auto filled by the uuid() function. One you done models go to generate the real database with migrate command
npx prisam migrate dev --name init
This will generate the tables using the models we defined, to make sure we can use the prisma studio which runs on the port 555, also a standalone studio app is available.
In the future we can modify and rerun the migrate command for updating the tables, which will drop the tables and re-create for us.
// run in new terminal
npmx prisma studio
How to use in our Nuxtjs app
In the nuxtjs app we need the dependency @prisma/client, let’s add them to our project
nmp i -s @prisma/client
In the Nuxt app , we can setup internal API for interacting with database using server middleware.
API routes
In the project folder create a folder api and inside the folder create a file index.ts
For create routes, we can use the express framework the API should export the handler as in Nextjs.
index.ts
import express from "express";
import { PrismaClient, Todo } from "@prisma/client";
const app = express();
const prisma = new PrismaClient();
app.use(express.json());
app.get("/", (req, res) => {
res.json("Wlcome to API");
});
app.get("/todos", async (req, res) => {
const todos = await prisma.todo.findMany();
res.json(todos);
});
export default {
path: "/api",
handler: app
};
Nuxt-config
For using Prisma client we need to use PrismaClient object. The API would not work at this point, it also required setup a middleware in the dedicated nuxt-config.
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
serverMiddleware:[
'~/api/index.ts',
] ,
.....
and now the api can be accessed at http://localhost:3000/api