feat: add prisma

This commit is contained in:
Daniel Soares
2021-12-13 15:34:37 -03:00
parent c7dc121d9e
commit 8c37b851f3
12 changed files with 341 additions and 7 deletions

View File

@@ -2,6 +2,7 @@ import { isEqual } from 'lodash'
import { useEffect, useState } from 'react'
import { useData } from '../../contexts/DataContext'
import { api } from '../../services/api'
import { theme } from '../../styles/stitches.config'
import {
getLocalStorageData,
@@ -38,6 +39,16 @@ export function Dash() {
}
}, [data, initialData])
const handleSave = async () => {
try {
await api.put('data', { data })
setHasUnsavedChanges(false)
removeLocalStorageData()
} catch (error) {
console.error(error)
}
}
const handleChangeBackground = (background: string) => {
setData({
...data,
@@ -64,7 +75,14 @@ export function Dash() {
return (
<Wrapper>
<Content>
<h1>Dash {hasUnsavedChanges && '- has unsaved changes'}</h1>
<h1>
Dash{' '}
{hasUnsavedChanges && (
<>
- has unsaved changes <button onClick={() => handleSave()}>save</button>
</>
)}
</h1>
<NameInput />
<DescriptionInput />

38
src/pages/api/data.ts Normal file
View File

@@ -0,0 +1,38 @@
import { NextApiRequest, NextApiResponse } from 'next'
import nc from 'next-connect'
import { prisma } from '../../services/prisma'
const { RAILWAY_TOKEN } = process.env
const handler = nc<NextApiRequest, NextApiResponse>()
.get(async (_req, res) => {
try {
const data = await prisma.data.findFirst()
res.status(200).json(data?.data)
} catch (error) {
console.error(error)
res.status(500).send('Internal server error')
}
})
.put(async (req, res) => {
try {
const response = await prisma.data.update({
where: {
id: 1
},
data: { data: JSON.stringify(req.body.data) }
})
if (RAILWAY_TOKEN) {
console.log('railway token', RAILWAY_TOKEN)
}
res.status(200).json(response)
} catch (error) {
console.error(error)
res.status(500).send('Internal server error')
}
})
export default handler

7
src/services/api.ts Normal file
View File

@@ -0,0 +1,7 @@
import axios from 'axios'
const { RAILWAY_STATIC_URL } = process.env
export const api = axios.create({
baseURL: `${RAILWAY_STATIC_URL}/api` || 'http://localhost:3000/api'
})

9
src/services/prisma.ts Normal file
View File

@@ -0,0 +1,9 @@
import { PrismaClient } from '@prisma/client'
declare global {
var prisma: PrismaClient | undefined
}
export const prisma = global.prisma || new PrismaClient()
if (process.env.NODE_ENV !== 'production') global.prisma = prisma