diff --git a/README.md b/README.md
index 9f309f4..b7752bf 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,321 @@
-# API Gain
+# REST API Example
-Api Gain - The Tip Top
+This example shows how to implement a **REST API with TypeScript** using [Express](https://expressjs.com/) and [Prisma Client](https://www.prisma.io/docs/concepts/components/prisma-client). The example uses an SQLite database file with some initial dummy data which you can find at [`./prisma/dev.db`](./prisma/dev.db).
## Getting started
+### 1. Download example and install dependencies
+
+Download this example:
+
+```
+npx try-prisma --template typescript/rest-express
+```
+
+Install npm dependencies:
+
+```
+cd rest-express
+npm install
+```
+
+Alternative: Clone the entire repo
+
+Clone this repository:
+
+```
+git clone git@github.com:prisma/prisma-examples.git --depth=1
+```
+
Install npm dependencies:
```
+cd prisma-examples/typescript/rest-express
npm install
```
+
+
+### 2. Create and seed the database
+
+Run the following command to create your SQLite database file. This also creates the `User` and `Post` tables that are defined in [`prisma/schema.prisma`](./prisma/schema.prisma):
+
+```
+npx prisma migrate dev --name init
+```
+
+When `npx prisma migrate dev` is executed against a newly created database, seeding is also triggered. The seed file in [`prisma/seed.ts`](./prisma/seed.ts) will be executed and your database will be populated with the sample data.
+
+
+### 3. Start the REST API server
+
+```
+npm run dev
+```
+
+The server is now running on `http://localhost:3000`. You can now run the API requests, e.g. [`http://localhost:3000/feed`](http://localhost:3000/feed).
+
+## Using the REST API
+
+You can access the REST API of the server using the following endpoints:
+
+### `GET`
+
+- `/post/:id`: Fetch a single post by its `id`
+- `/feed?searchString={searchString}&take={take}&skip={skip}&orderBy={orderBy}`: Fetch all _published_ posts
+ - Query Parameters
+ - `searchString` (optional): This filters posts by `title` or `content`
+ - `take` (optional): This specifies how many objects should be returned in the list
+ - `skip` (optional): This specifies how many of the returned objects in the list should be skipped
+ - `orderBy` (optional): The sort order for posts in either ascending or descending order. The value can either `asc` or `desc`
+- `/user/:id/drafts`: Fetch user's drafts by their `id`
+- `/users`: Fetch all users
+### `POST`
+
+- `/post`: Create a new post
+ - Body:
+ - `title: String` (required): The title of the post
+ - `content: String` (optional): The content of the post
+ - `authorEmail: String` (required): The email of the user that creates the post
+- `/signup`: Create a new user
+ - Body:
+ - `email: String` (required): The email address of the user
+ - `name: String` (optional): The name of the user
+ - `postData: PostCreateInput[]` (optional): The posts of the user
+
+### `PUT`
+
+- `/publish/:id`: Toggle the publish value of a post by its `id`
+- `/post/:id/views`: Increases the `viewCount` of a `Post` by one `id`
+
+### `DELETE`
+
+- `/post/:id`: Delete a post by its `id`
+
+
+## Evolving the app
+
+Evolving the application typically requires two steps:
+
+1. Migrate your database using Prisma Migrate
+1. Update your application code
+
+For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.
+
+### 1. Migrate your database using Prisma Migrate
+
+The first step is to add a new table, e.g. called `Profile`, to the database. You can do this by adding a new model to your [Prisma schema file](./prisma/schema.prisma) file and then running a migration afterwards:
+
+```diff
+// ./prisma/schema.prisma
+
+model User {
+ id Int @default(autoincrement()) @id
+ name String?
+ email String @unique
+ posts Post[]
++ profile Profile?
+}
+
+model Post {
+ id Int @id @default(autoincrement())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ title String
+ content String?
+ published Boolean @default(false)
+ viewCount Int @default(0)
+ author User? @relation(fields: [authorId], references: [id])
+ authorId Int?
+}
+
++model Profile {
++ id Int @default(autoincrement()) @id
++ bio String?
++ user User @relation(fields: [userId], references: [id])
++ userId Int @unique
++}
+```
+
+Once you've updated your data model, you can execute the changes against your database with the following command:
+
+```
+npx prisma migrate dev --name add-profile
+```
+
+This adds another migration to the `prisma/migrations` directory and creates the new `Profile` table in the database.
+
+### 2. Update your application code
+
+You can now use your `PrismaClient` instance to perform operations against the new `Profile` table. Those operations can be used to implement API endpoints in the REST API.
+
+#### 2.1 Add the API endpoint to your app
+
+Update your `index.ts` file by adding a new endpoint to your API:
+
+```ts
+app.post('/user/:id/profile', async (req, res) => {
+ const { id } = req.params
+ const { bio } = req.body
+
+ const profile = await prisma.profile.create({
+ data: {
+ bio,
+ user: {
+ connect: {
+ id: Number(id)
+ }
+ }
+ }
+ })
+
+ res.json(profile)
+})
+```
+
+#### 2.2 Testing out your new endpoint
+
+Restart your application server and test out your new endpoint.
+
+##### `POST`
+
+- `/user/:id/profile`: Create a new profile based on the user id
+ - Body:
+ - `bio: String` : The bio of the user
+
+
+Expand to view more sample Prisma Client queries on Profile
+
+Here are some more sample Prisma Client queries on the new Profile model:
+
+##### Create a new profile for an existing user
+
+```ts
+const profile = await prisma.profile.create({
+ data: {
+ bio: 'Hello World',
+ user: {
+ connect: { email: 'alice@prisma.io' },
+ },
+ },
+})
+```
+
+##### Create a new user with a new profile
+
+```ts
+const user = await prisma.user.create({
+ data: {
+ email: 'john@prisma.io',
+ name: 'John',
+ profile: {
+ create: {
+ bio: 'Hello World',
+ },
+ },
+ },
+})
+```
+
+##### Update the profile of an existing user
+
+```ts
+const userWithUpdatedProfile = await prisma.user.update({
+ where: { email: 'alice@prisma.io' },
+ data: {
+ profile: {
+ update: {
+ bio: 'Hello Friends',
+ },
+ },
+ },
+})
+```
+
+
+
+## Switch to another database (e.g. PostgreSQL, MySQL, SQL Server, MongoDB)
+
+If you want to try this example with another database than SQLite, you can adjust the the database connection in [`prisma/schema.prisma`](./prisma/schema.prisma) by reconfiguring the `datasource` block.
+
+Learn more about the different connection configurations in the [docs](https://www.prisma.io/docs/reference/database-reference/connection-urls).
+
+Expand for an overview of example configurations with different databases
+
+### PostgreSQL
+
+For PostgreSQL, the connection URL has the following structure:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+ url = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
+}
+```
+
+Here is an example connection string with a local PostgreSQL database:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+ url = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
+}
+```
+
+### MySQL
+
+For MySQL, the connection URL has the following structure:
+
+```prisma
+datasource db {
+ provider = "mysql"
+ url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
+}
+```
+
+Here is an example connection string with a local MySQL database:
+
+```prisma
+datasource db {
+ provider = "mysql"
+ url = "mysql://janedoe:mypassword@localhost:3306/notesapi"
+}
+```
+
+### Microsoft SQL Server
+
+Here is an example connection string with a local Microsoft SQL Server database:
+
+```prisma
+datasource db {
+ provider = "sqlserver"
+ url = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
+}
+```
+
+### MongoDB
+
+Here is an example connection string with a local MongoDB database:
+
+```prisma
+datasource db {
+ provider = "mongodb"
+ url = "mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin&retryWrites=true&w=majority"
+}
+```
+Because MongoDB is currently in [Preview](https://www.prisma.io/docs/about/releases#preview), you need to specify the `previewFeatures` on your `generator` block:
+
+```
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["mongodb"]
+}
+```
+
+
+## Next steps
+
+- Check out the [Prisma docs](https://www.prisma.io/docs)
+- Share your feedback in the [`prisma2`](https://prisma.slack.com/messages/CKQTGR6T0/) channel on the [Prisma Slack](https://slack.prisma.io/)
+- Create issues and ask questions on [GitHub](https://github.com/prisma/prisma/)
+- Watch our biweekly "What's new in Prisma" livestreams on [Youtube](https://www.youtube.com/channel/UCptAHlN1gdwD89tFM3ENb6w)
diff --git a/enum/cadeaux.enum.ts b/enum/cadeaux.enum.ts
new file mode 100644
index 0000000..e12f141
--- /dev/null
+++ b/enum/cadeaux.enum.ts
@@ -0,0 +1,7 @@
+export enum Cadeaux {
+ GrandCoffretDecouverte = 1,
+ CoffretDecouverte = 2,
+ TheSignature = 3,
+ TheDetox = 4,
+ Infuseur = 5,
+}
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 967885f..2d4aaa3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,7 +11,8 @@
"dependencies": {
"@prisma/client": "4.7.1",
"dotenv": "^16.0.3",
- "express": "4.18.2"
+ "express": "4.18.2",
+ "node-fetch": "^2.6.7"
},
"devDependencies": {
"@types/express": "4.17.14",
@@ -819,6 +820,25 @@
"node": ">= 0.6"
}
},
+ "node_modules/node-fetch": {
+ "version": "2.6.7",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
+ "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
+ "dependencies": {
+ "whatwg-url": "^5.0.0"
+ },
+ "engines": {
+ "node": "4.x || >=6.0.0"
+ },
+ "peerDependencies": {
+ "encoding": "^0.1.0"
+ },
+ "peerDependenciesMeta": {
+ "encoding": {
+ "optional": true
+ }
+ }
+ },
"node_modules/nodemon": {
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.20.tgz",
@@ -1179,6 +1199,11 @@
"nodetouch": "bin/nodetouch.js"
}
},
+ "node_modules/tr46": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
+ },
"node_modules/ts-node": {
"version": "10.9.1",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz",
@@ -1295,6 +1320,20 @@
"node": ">= 0.8"
}
},
+ "node_modules/webidl-conversions": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
+ },
+ "node_modules/whatwg-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "dependencies": {
+ "tr46": "~0.0.3",
+ "webidl-conversions": "^3.0.0"
+ }
+ },
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
@@ -1922,6 +1961,14 @@
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="
},
+ "node-fetch": {
+ "version": "2.6.7",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
+ "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
+ "requires": {
+ "whatwg-url": "^5.0.0"
+ }
+ },
"nodemon": {
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.20.tgz",
@@ -2181,6 +2228,11 @@
"nopt": "~1.0.10"
}
},
+ "tr46": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
+ },
"ts-node": {
"version": "10.9.1",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz",
@@ -2250,6 +2302,20 @@
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="
},
+ "webidl-conversions": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
+ },
+ "whatwg-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "requires": {
+ "tr46": "~0.0.3",
+ "webidl-conversions": "^3.0.0"
+ }
+ },
"yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
diff --git a/package.json b/package.json
index 1601396..bdf8a6e 100644
--- a/package.json
+++ b/package.json
@@ -3,12 +3,14 @@
"version": "1.0.0",
"license": "MIT",
"scripts": {
- "dev": "ts-node src/index.ts"
+ "dev": "ts-node src/index.ts",
+ "start": "npx nodemon src/index.ts"
},
"dependencies": {
"@prisma/client": "4.7.1",
"dotenv": "^16.0.3",
- "express": "4.18.2"
+ "express": "4.18.2",
+ "node-fetch": "^2.6.7"
},
"devDependencies": {
"@types/express": "4.17.14",
@@ -18,8 +20,5 @@
"prisma": "4.7.1",
"ts-node": "10.9.1",
"typescript": "4.9.4"
- },
- "prisma": {
- "seed": "ts-node prisma/seed.ts"
}
}
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 98e1748..f46efb8 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -60,11 +60,6 @@ model User {
@@map(name: "users")
}
-model TicketsRestants {
- id Int @id @default(autoincrement())
- total Int
-}
-
model Gain {
id Int @id @default(autoincrement())
codeCadeau String @unique
diff --git a/src/index.ts b/src/index.ts
index abe2284..903d7f8 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,7 +1,11 @@
-import { Gain, Prisma, PrismaClient } from '@prisma/client'
-import express from 'express'
+import express, { Request, Response } from 'express'
import dotenv from 'dotenv'
+import { Gain, PrismaClient } from '@prisma/client'
+import { Cadeaux } from '../enum/cadeaux.enum';
+import process from 'process';
+import { makeGain } from '../utils/makeGain';
+
//chargement des variables d'environnement
dotenv.config()
@@ -12,30 +16,79 @@ const prisma = new PrismaClient()
const app = express()
app.use(express.json())
-const PORT = process.env.NODE_DOCKER_PORT || 8990;
+const PORT = process.env.NODE_DOCKER_PORT || 3001;
+
+/**
+ * Attribution d'un gain à un ticket
+ */
+app.get('/getgain', async (req: Request, res: Response) => {
+ const { sum } = req.query;
-app.get('/feed', async (req, res) => {
+ //vérifie que la somme renvoyé par la caisse est surpérieru à 49€
+ if (Number(sum) < 49) {
+ return res.status(402).json({ message: 'Montant inférieur à 49€', })
+ }
try {
//selectionne un code gain de façon aléatoire
const randomGain: Gain[] = await prisma.$queryRawUnsafe(
`SELECT * FROM public."Gain" WHERE "dateAchat" IS NULL ORDER BY RANDOM() LIMIT 1;`,
)
-
//met à jour la date d'achat du gain séléctionné
const updatedGain: Gain = await prisma.gain.update({
where: {
id: randomGain[0].id,
},
data: {
+ codeActif: true,
dateAchat: new Date(),
}
})
- res.json({ message: 'Emission de numero sur un ticket', number: updatedGain.codeCadeau, date: updatedGain.dateAchat })
+ res.status(200).json({
+ message: 'Emission de numero sur un ticket : Succès',
+ number: updatedGain.codeCadeau,
+ date: updatedGain.dateAchat
+ })
} catch (error) {
- console.log('oups!', error)
+ console.log('Erreur : ', error)
}
})
-app.listen(PORT, () => console.log(`🚀 Server ready at PORT : ${PORT}`),
+
+/**
+ * Génération des 1 500 000 tickets
+ */
+app.get('/generate', async (req: Request, res: Response,) => {
+
+ if (!process.env.GENERATE_TICKET) {
+ return res.status(401).json({ message: 'Unauthorized' })
+ }
+ try {
+ // makeGain(100, Cadeaux.GrandCoffretDecouverte)
+
+ makeGain(60000, Cadeaux.GrandCoffretDecouverte)
+ makeGain(90000, Cadeaux.CoffretDecouverte)
+ makeGain(150000, Cadeaux.TheSignature)
+
+ for (let i = 0; i < 2; i++) {
+ makeGain(150000, Cadeaux.TheDetox)
+ }
+
+ for (let i = 0; i < 6; i++) {
+ makeGain(150000, Cadeaux.Infuseur)
+ }
+
+
+ const totalGains = await prisma.gain.count({})
+
+ console.log('total', totalGains);
+
+ return res.status(200).json({ message: 'Gains generés !', totalGains: totalGains });
+ } catch (error) {
+ return res.status(500).json({ error: error });
+ }
+
+})
+
+app.listen(PORT, () => console.log(`🚀 API GAIN - Server ready at PORT : ${PORT}`),
)
diff --git a/tsconfig.json b/tsconfig.json
index 86758c0..1f3d89f 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -4,6 +4,12 @@
"outDir": "dist",
"strict": true,
"lib": ["esnext"],
- "esModuleInterop": true
- }
+ "esModuleInterop": true,
+
+ },
+ "ts-node": {
+ "esm": true,
+ "experimentalSpecifierResolution": "node",
+}
+
}
diff --git a/utils/makeGain.ts b/utils/makeGain.ts
new file mode 100644
index 0000000..d02a293
--- /dev/null
+++ b/utils/makeGain.ts
@@ -0,0 +1,36 @@
+
+import { Gain, Prisma, PrismaClient } from '@prisma/client'
+
+import { Cadeaux } from '../enum/cadeaux.enum'
+
+//instance du client prisma
+const prisma = new PrismaClient()
+
+
+export const makeGain = async (nbrGain: number, idProduit: number) => {
+ let generatedGains: any[] = [];
+ let code: string = '';
+ let i: number = 0;
+
+ //creation d'un nombre de gain
+ for (; i < nbrGain; i++) {
+ code = Array.from({ length: 10 }, () => Math.random().toString(36)[2]).join('').toUpperCase();
+ generatedGains.push({
+ codeActif: true,
+ retrait: false,
+ produitId: idProduit,
+ codeCadeau: code
+ })
+
+ console.log(`produit : ${Cadeaux[idProduit]}, n° : ${i}`)
+ }
+
+
+
+
+ const res = await prisma.gain.createMany({
+ data: generatedGains
+ })
+
+ console.log('YEYEEEEEEEEEEEEE', res);
+}