Maison > interface Web > js tutoriel > le corps du texte

Création d'une API RESTful avec Prisma, Express, TypeScript et PostgreSQL

WBOY
Libérer: 2024-09-07 06:31:32
original
791 Les gens l'ont consulté

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

Table des matières

  1. Présentation

    • Présentation de Prisma, Express, TypeScript et PostgreSQL
    • Pourquoi Prisma comme ORM ?
    • Configuration de l'environnement
  2. Configuration initiale du projet

    • Configuration d'un nouveau projet Node.js
    • Configuration de TypeScript
    • Installation des packages requis
  3. Configuration de PostgreSQL

    • Installation de PostgreSQL
    • Création d'une nouvelle base de données
    • Configuration des variables d'environnement
  4. Configuration de Prisma

    • Installation de Prisma
    • Initialisation de Prisma dans le projet
    • Configuration du schéma Prisma
  5. Définir le modèle de données

    • Comprendre le langage de schéma Prisma (PSL)
    • Création de modèles pour l'API
    • Migrations avec Prisma
  6. Intégrer Prisma avec Express

    • Configuration du serveur Express
    • Création d'opérations CRUD avec Prisma
    • Gestion des erreurs et validation
  7. Utiliser TypeScript pour la sécurité des types

    • Définir des types avec Prisma
    • Requêtes et mutations de type sécurisé
    • Exploiter TypeScript dans le développement d'API
  8. Test de l'API

    • Écriture de tests unitaires pour les modèles Prisma
    • Tests d'intégration avec Supertest et Jest
    • Se moquer de la base de données avec Prisma
  9. Considérations sur le déploiement

    • Préparer l'API pour la production
    • Déploiement de PostgreSQL
    • Déploiement de l'application Node.js
  10. Conclusion

    • Avantages de l'utilisation de Prisma avec Express et TypeScript
    • Réflexions finales et prochaines étapes

1. Introduction

Présentation de Prisma, Express, TypeScript et PostgreSQL

Dans le développement Web moderne, la création d'API robustes, évolutives et sécurisées est cruciale. En combinant la puissance de Prisma en tant qu'ORM, Express pour la logique côté serveur, TypeScript pour le typage statique et PostgreSQL en tant que solution de base de données fiable, nous pouvons créer une puissante API RESTful.

Prisma simplifie la gestion des bases de données en fournissant un ORM moderne qui prend en charge les requêtes de type sécurisé, les migrations et la gestion transparente des schémas de base de données. Express est un framework d'application Web Node.js minimal et flexible qui fournit un ensemble robuste de fonctionnalités pour les applications Web et mobiles. TypeScript ajoute des définitions de types statiques à JavaScript, aidant ainsi à détecter les erreurs dès le début du processus de développement. PostgreSQL est un système de base de données relationnelle puissant et open source connu pour sa fiabilité et son ensemble de fonctionnalités.

Pourquoi Prisma comme ORM ?

Prisma offre plusieurs avantages par rapport aux ORM traditionnels comme Sequelize et TypeORM :

  • Requêtes de base de données de type sécurisé : Les types générés automatiquement garantissent que vos requêtes de base de données sont de type sécurisé et sans erreur.
  • Migrations automatisées : Prisma fournit un système de migration puissant qui maintient le schéma de votre base de données synchronisé avec votre schéma Prisma.
  • Modélisation intuitive des données : Le fichier de schéma Prisma (écrit en PSL) est facile à comprendre et à maintenir.
  • Écosystème étendu : Prisma s'intègre de manière transparente à d'autres outils et services, notamment GraphQL, les API REST et des bases de données populaires telles que PostgreSQL.

Configuration de l'environnement

Avant de plonger dans le code, assurez-vous que les outils suivants sont installés sur votre machine :

  • Node.js (version LTS recommandée)
  • npm ou Yarn (pour la gestion des colis)
  • TypeScript (pour le typage statique)
  • PostgreSQL (comme notre base de données)

Une fois ces outils installés, nous pouvons commencer à construire notre API.


2. Configuration initiale du projet

Configuration d'un nouveau projet Node.js

  1. Créez un nouveau répertoire de projet :
   mkdir prisma-express-api
   cd prisma-express-api
Copier après la connexion
  1. Initialiser un nouveau projet Node.js :
   npm init -y
Copier après la connexion

Cela créera un fichier package.json dans le répertoire de votre projet.

Configuration de TypeScript

  1. Installer les types TypeScript et Node.js :
   npm install typescript @types/node --save-dev
Copier après la connexion
  1. Initialisez TypeScript dans votre projet :
   npx tsc --init
Copier après la connexion

Cette commande crée un fichier tsconfig.json, qui est le fichier de configuration de TypeScript. Modifiez-le selon les besoins de votre projet. Voici une configuration de base :

   {
     "compilerOptions": {
       "target": "ES2020",
       "module": "commonjs",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true,
       "outDir": "./dist"
     },
     "include": ["src/**/*"]
   }
Copier après la connexion
  1. Créer la structure du projet :
   mkdir src
   touch src/index.ts
Copier après la connexion

Installation des packages requis

Pour commencer avec Express et Prisma, vous devrez installer quelques packages essentiels :

npm install express prisma @prisma/client
npm install --save-dev ts-node nodemon @types/express
Copier après la connexion
  • 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
Copier après la connexion

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;
Copier après la connexion

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"
Copier après la connexion

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
Copier après la connexion

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])
}
Copier après la connexion

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
Copier après la connexion

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}`);
});
Copier après la connexion

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);
});
Copier après la connexion

Read all users:


app.get('/users', async (req: Request, res: Response) => {
  const users = await prisma.user.findMany();
  res.json(users);
});
Copier après la connexion

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);
});
Copier après la connexion

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);
});
Copier après la connexion

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' });
  }
});
Copier après la connexion

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.
});
Copier après la connexion

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();
Copier après la connexion

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
Copier après la connexion

Create a jest.config.js file:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Copier après la connexion

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');
});
Copier après la connexion

Integration Testing with Supertest and Jest

You can also write integration tests using Supertest:

npm install supertest --save-dev
Copier après la connexion

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);
});
Copier après la connexion

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!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!