33require ( 'dotenv' ) . config ( ) ;
44const express = require ( 'express' ) ;
55const dbService = require ( './dbService' ) ;
6-
76const app = express ( ) ;
87app . use ( express . json ( ) ) ;
98
@@ -14,25 +13,41 @@ app.listen(PORT, () => {
1413} ) ;
1514
1615app . get ( '/hello-world' , ( req , res ) => {
17- res . send ( { ' message' : 'hello world!' } )
16+ res . send ( { message : 'hello world!' } )
1817} ) ;
1918
20- app . get ( '/users' , async ( req , res ) => {
19+ app . get ( '/users' , async ( req , res ) => {
2120 try {
2221 const data = await dbService . getUsers ( ) ;
2322 res . json ( data ) ;
24- } catch ( err ) {
25- res . status ( 500 ) . json ( { ' message' : 'Connection to the SQL server failed' } )
23+ } catch ( error ) {
24+ res . status ( 500 ) . json ( { message : 'Connection to the SQL server failed' } )
2625 }
2726} ) ;
2827
29- app . get ( '/users/:cpf' , async ( req , res ) => {
28+ app . get ( '/users/:cpf' , async ( req , res ) => {
3029 try {
3130 const user = await dbService . getUserByCpf ( req . params . cpf ) ;
3231 user . length === 1
3332 ? res . json ( user )
34- : res . status ( 404 ) . send ( { 'message' :'User not found' } ) ;
35- } catch ( err ) {
36- res . status ( 500 ) . json ( { 'message' :'Connection to the SQL server failed' } )
33+ : res . status ( 404 ) ;
34+ } catch ( error ) {
35+ res . status ( 500 ) . json ( { message : 'Connection to the SQL server failed' } )
36+ }
37+ } ) ;
38+
39+ app . post ( '/users' , async ( req , res ) => {
40+ const { cpf, fullName, password } = req . body ;
41+ try {
42+ const createdUser = await dbService . createUser ( cpf , fullName , password ) ;
43+ const { password : _ , ...userData } = createdUser ;
44+ res . status ( 201 ) . send ( userData )
45+ } catch ( error ) {
46+ if ( error . code === '23505' )
47+ res . status ( 409 ) . send ( { message : 'User with this CPF already exists' } ) ;
48+ else if ( error . code === '22001' )
49+ res . status ( 400 ) . send ( { message : error . message } ) ;
50+ else
51+ res . status ( 500 ) . send ( { message : error . message } )
3752 }
38- } ) ;
53+ } )
0 commit comments