Skip to content

Instantly share code, notes, and snippets.

@mcavalcantib
Last active February 1, 2023 23:16
Show Gist options
  • Select an option

  • Save mcavalcantib/87874e0e90b7c52efcf12aec09a2ce79 to your computer and use it in GitHub Desktop.

Select an option

Save mcavalcantib/87874e0e90b7c52efcf12aec09a2ce79 to your computer and use it in GitHub Desktop.
Nodejs example using fastify and prisma
import React, { useState } from 'react';
interface FormData {
name: string;
address: string;
}
const UserForm: React.FC = () => {
const [formData, setFormData] = useState<FormData>({ name: '', address: '' });
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const response = await fetch('/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="address">Address:</label>
<input
type="text"
id="address"
name="address"
value={formData.address}
onChange={handleChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default UserForm;
import * as Fastify from 'fastify'
import { PrismaClient } from '@prisma/client'
const app = Fastify({
logger: true
})
const prisma = new PrismaClient()
app.get('/', async (request, reply) => {
reply.send({ hello: 'world' })
})
app.post('/user', async (request, reply) => {
const body = request.body
if (!body.name || !body.address) {
reply.code(400).send({ error: 'Name and address are required' })
} else {
await prisma.user.create({
data: {
name: body.name,
address: body.address
}
})
reply.send({ sucesso: 'User sucessfuly created' })
}
})
app.listen(3000, (err, address) => {
if (err) {
app.log.error(err)
process.exit(1)
}
app.log.info(`server listening on ${address}`)
})
process.on('SIGINT', async () => {
await prisma.disconnect()
process.exit()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment