Heim > Web-Frontend > js-Tutorial > Hauptteil

Erstellen einer RESTful-API mit Prisma, Express, TypeScript und PostgreSQL

WBOY
Freigeben: 2024-09-07 06:31:32
Original
702 Leute haben es durchsucht

Building a RESTful API with Prisma, Express, TypeScript, and PostgreSQL

Inhaltsverzeichnis

  1. Einführung

    • Überblick über Prisma, Express, TypeScript und PostgreSQL
    • Warum Prisma als ORM?
    • Einrichten der Umgebung
  2. Erste Projekteinrichtung

    • Einrichten eines neuen Node.js-Projekts
    • TypeScript konfigurieren
    • Erforderliche Pakete installieren
  3. PostgreSQL einrichten

    • PostgreSQL installieren
    • Erstellen einer neuen Datenbank
    • Umgebungsvariablen konfigurieren
  4. Prisma einrichten

    • Prisma installieren
    • Prisma im Projekt initialisieren
    • Konfigurieren des Prisma-Schemas
  5. Definieren des Datenmodells

    • Prisma Schema Language (PSL) verstehen
    • Modelle für die API erstellen
    • Migrationen mit Prisma
  6. Integration von Prisma mit Express

    • Einrichten des Express-Servers
    • CRUD-Operationen mit Prisma erstellen
    • Fehlerbehandlung und Validierung
  7. TypeScript für Typsicherheit verwenden

    • Typen mit Prisma definieren
    • Typsichere Abfragen und Mutationen
    • TypeScript in der API-Entwicklung nutzen
  8. Testen der API

    • Schreiben von Unit-Tests für Prisma-Modelle
    • Integrationstests mit Supertest und Jest
    • Verspottung der Datenbank mit Prisma
  9. Überlegungen zur Bereitstellung

    • Vorbereitung der API für die Produktion
    • Bereitstellung von PostgreSQL
    • Bereitstellen der Node.js-Anwendung
  10. Fazit

    • Vorteile der Verwendung von Prisma mit Express und TypeScript
    • Abschließende Gedanken und nächste Schritte

1. Einführung

Übersicht über Prisma, Express, TypeScript und PostgreSQL

In der modernen Webentwicklung ist der Aufbau robuster, skalierbarer und typsicherer APIs von entscheidender Bedeutung. Durch die Kombination der Leistungsfähigkeit von Prisma als ORM, Express für serverseitige Logik, TypeScript für statische Typisierung und PostgreSQL als zuverlässige Datenbanklösung können wir eine leistungsstarke RESTful-API erstellen.

Prisma vereinfacht die Datenbankverwaltung durch die Bereitstellung eines modernen ORM, das typsichere Abfragen, Migrationen und eine nahtlose Datenbankschemaverwaltung unterstützt. Express ist ein minimales und flexibles Node.js-Webanwendungsframework, das eine Reihe robuster Funktionen für Web- und mobile Anwendungen bietet. TypeScript fügt JavaScript statische Typdefinitionen hinzu und hilft so, Fehler frühzeitig im Entwicklungsprozess zu erkennen. PostgreSQL ist ein leistungsstarkes relationales Open-Source-Datenbanksystem, das für seine Zuverlässigkeit und seinen Funktionsumfang bekannt ist.

Warum Prisma als ORM?

Prisma bietet mehrere Vorteile gegenüber herkömmlichen ORMs wie Sequelize und TypeORM:

  • Typsichere Datenbankabfragen: Automatisch generierte Typen stellen sicher, dass Ihre Datenbankabfragen typsicher und fehlerfrei sind.
  • Automatisierte Migrationen: Prisma bietet ein leistungsstarkes Migrationssystem, das Ihr Datenbankschema mit Ihrem Prisma-Schema synchronisiert.
  • Intuitive Datenmodellierung: Die Prisma-Schemadatei (geschrieben in PSL) ist leicht zu verstehen und zu verwalten.
  • Umfangreiches Ökosystem: Prisma lässt sich nahtlos in andere Tools und Dienste integrieren, einschließlich GraphQL, REST-APIs und beliebte Datenbanken wie PostgreSQL.

Einrichten der Umgebung

Bevor wir uns mit dem Code befassen, stellen Sie sicher, dass die folgenden Tools auf Ihrem Computer installiert sind:

  • Node.js (LTS-Version empfohlen)
  • npm oder Yarn (zur Paketverwaltung)
  • TypeScript (für statisches Tippen)
  • PostgreSQL (als unsere Datenbank)

Sobald diese Tools installiert sind, können wir mit dem Aufbau unserer API beginnen.


2. Ersteinrichtung des Projekts

Einrichten eines neuen Node.js-Projekts

  1. Neues Projektverzeichnis erstellen:
   mkdir prisma-express-api
   cd prisma-express-api
Nach dem Login kopieren
  1. Initialisieren Sie ein neues Node.js-Projekt:
   npm init -y
Nach dem Login kopieren

Dadurch wird eine package.json-Datei in Ihrem Projektverzeichnis erstellt.

TypeScript konfigurieren

  1. TypeScript- und Node.js-Typen installieren:
   npm install typescript @types/node --save-dev
Nach dem Login kopieren
  1. Initialisieren Sie TypeScript in Ihrem Projekt:
   npx tsc --init
Nach dem Login kopieren

Dieser Befehl erstellt eine tsconfig.json-Datei, die die Konfigurationsdatei für TypeScript ist. Ändern Sie es nach Bedarf für Ihr Projekt. Hier ist eine Grundeinstellung:

   {
     "compilerOptions": {
       "target": "ES2020",
       "module": "commonjs",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true,
       "outDir": "./dist"
     },
     "include": ["src/**/*"]
   }
Nach dem Login kopieren
  1. Erstellen Sie die Projektstruktur:
   mkdir src
   touch src/index.ts
Nach dem Login kopieren

Erforderliche Pakete installieren

Um mit Express und Prisma zu beginnen, müssen Sie einige wichtige Pakete installieren:

npm install express prisma @prisma/client
npm install --save-dev ts-node nodemon @types/express
Nach dem Login kopieren
  • express: The web framework for Node.js.
  • prisma: The Prisma CLI for database management.
  • @prisma/client: The Prisma client for querying the database.
  • ts-node: Runs TypeScript directly without the need for precompilation.
  • nodemon: Automatically restarts the server on file changes.
  • @types/express: TypeScript definitions for Express.

3. Setting Up PostgreSQL

Installing PostgreSQL

PostgreSQL can be installed via your operating system’s package manager or directly from the official website. For example, on macOS, you can use Homebrew:

brew install postgresql
brew services start postgresql
Nach dem Login kopieren

Creating a New Database

Once PostgreSQL is installed and running, you can create a new database for your project:

psql postgres
CREATE DATABASE prisma_express;
Nach dem Login kopieren

Replace prisma_express with your preferred database name.

Configuring Environment Variables

To connect to the PostgreSQL database, create a .env file in your project’s root directory and add the following environment variables:

DATABASE_URL="postgresql://<user>:<password>@localhost:5432/prisma_express"
Nach dem Login kopieren

Replace and with your PostgreSQL username and password. This connection string will be used by Prisma to connect to your PostgreSQL database.


4. Setting Up Prisma

Installing Prisma

Prisma is already installed in the previous step, so the next step is to initialize it within the project:

npx prisma init
Nach dem Login kopieren

This command will create a prisma directory containing a schema.prisma file and a .env file. The .env file should already contain the DATABASE_URL you specified earlier.

Configuring the Prisma Schema

The schema.prisma file is where you'll define your data models, which will be used to generate database tables.

Here’s a basic example schema:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  createdAt DateTime @default(now())
  posts     Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])
}
Nach dem Login kopieren

In this schema, we have two models: User and Post. Each model corresponds to a database table. Prisma uses these models to generate type-safe queries for our database.


5. Defining the Data Model

Understanding Prisma Schema Language (PSL)

Prisma Schema Language (PSL) is used to define your database schema. It's intuitive and easy to read, with a focus on simplicity. Each model in the schema represents a table in your database, and each field corresponds to a column.

Creating Models for the API

In the schema defined earlier, we created two models:

  • User: Represents users in our application.
  • Post: Represents posts created by users.

Migrations with Prisma

To apply your schema changes to the database, you’ll need to run a migration:

npx prisma migrate dev --name init
Nach dem Login kopieren

This command will create a new migration file and apply it to your database, creating the necessary tables.


6. Integrating Prisma with Express

Setting Up the Express Server

In your src/index.ts, set up the basic Express server:

import express, { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';

const app = express();
const prisma = new PrismaClient();

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello, Prisma with Express!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Nach dem Login kopieren

This code sets up a simple Express server and initializes the Prisma client.

Creating CRUD Operations with Prisma

Next, let’s create some CRUD (Create, Read, Update, Delete) routes for our User model.

Create a new user:

app.post('/user', async (req: Request, res: Response) => {
  const { name, email } = req.body;
  const user = await prisma.user.create({
    data: { name, email },
  });
  res.json(user);
});
Nach dem Login kopieren

Read all users:


app.get('/users', async (req: Request, res: Response) => {
  const users = await prisma.user.findMany();
  res.json(users);
});
Nach dem Login kopieren

Update a user:

app.put('/user/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  const { name, email } = req.body;
  const user = await prisma.user.update({
    where: { id: Number(id) },
    data: { name, email },
  });
  res.json(user);
});
Nach dem Login kopieren

Delete a user:

app.delete('/user/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  const user = await prisma.user.delete({
    where: { id: Number(id) },
  });
  res.json(user);
});
Nach dem Login kopieren

Error Handling and Validation

To enhance the robustness of your API, consider adding error handling and validation:

app.post('/user', async (req: Request, res: Response) => {
  try {
    const { name, email } = req.body;
    if (!name || !email) {
      return res.status(400).json({ error: 'Name and email are required' });
    }
    const user = await prisma.user.create({
      data: { name, email },
    });
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});
Nach dem Login kopieren

7. Using TypeScript for Type Safety

Defining Types with Prisma

Prisma automatically generates TypeScript types for your models based on your schema. This ensures that your database queries are type-safe.

For example, when creating a new user, TypeScript will enforce the shape of the data being passed:

const user = await prisma.user.create({
  data: { name, email }, // TypeScript ensures 'name' and 'email' are strings.
});
Nach dem Login kopieren

Type-Safe Queries and Mutations

With TypeScript, you get autocomplete and type-checking for all Prisma queries, reducing the chance of runtime errors:

const users: User[] = await prisma.user.findMany();
Nach dem Login kopieren

Leveraging TypeScript in API Development

Using TypeScript throughout your API development helps catch potential bugs early, improves code readability, and enhances overall development experience.


8. Testing the API

Writing Unit Tests for Prisma Models

Testing is an essential part of any application development. You can write unit tests for your Prisma models using a testing framework like Jest:

npm install jest ts-jest @types/jest --save-dev
Nach dem Login kopieren

Create a jest.config.js file:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Nach dem Login kopieren

Example test for creating a user:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

test('should create a new user', async () => {
  const user = await prisma.user.create({
    data: {
      name: 'John Doe',
      email: 'john.doe@example.com',
    },
  });
  expect(user).toHaveProperty('id');
  expect(user.name).toBe('John Doe');
});
Nach dem Login kopieren

Integration Testing with Supertest and Jest

You can also write integration tests using Supertest:

npm install supertest --save-dev
Nach dem Login kopieren

Example integration test:

import request from 'supertest';
import app from './app'; // Your Express app

test('GET /users should return a list of users', async () => {
  const response = await request(app).get('/users');
  expect(response.status).toBe(200);
  expect(response.body).toBeInstanceOf(Array);
});
Nach dem Login kopieren

Mocking the Database with Prisma

For testing purposes, you might want to mock the Prisma client. You can do this using tools like jest.mock() or by creating a mock instance of the Prisma client.


9. Deployment Considerations

Preparing the API for Production

Before deploying your API, ensure you:

  • Remove all development dependencies.
  • Set up environment variables correctly.
  • Optimize the build process using tools like tsc and webpack.

Deploying PostgreSQL

You can deploy PostgreSQL using cloud services like AWS RDS, Heroku, or DigitalOcean. Make sure to secure your database with proper authentication and network settings.

Deploying the Node.js Application

For deploying the Node.js application, consider using services like:

  • Heroku: For simple, straightforward deployments.
  • AWS Elastic Beanstalk: For more control over the infrastructure.
  • Docker: To containerize the application and deploy it on any cloud platform.

10. Conclusion

Benefits of Using Prisma with Express and TypeScript

Using Prisma as an ORM with Express and TypeScript provides a powerful combination for building scalable, type-safe, and efficient RESTful APIs. With Prisma, you get automated migrations, type-safe queries, and an intuitive schema language, making database management straightforward and reliable.

Congratulations!! You've now built a robust RESTful API using Prisma, Express, TypeScript, and PostgreSQL. From setting up the environment to deploying the application, this guide covered the essential steps to get you started. As next steps, consider exploring advanced Prisma features like nested queries, transactions, and more complex data models.

Happy coding!

Das obige ist der detaillierte Inhalt vonErstellen einer RESTful-API mit Prisma, Express, TypeScript und PostgreSQL. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!