Skip to content

Commit

Permalink
Decompose users route
Browse files Browse the repository at this point in the history
  • Loading branch information
bcomnes committed Sep 6, 2022
1 parent 61329f5 commit 8b16383
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 38 deletions.
31 changes: 31 additions & 0 deletions routes/api/user/get-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { userJsonSchema } from './user-props.js'
import { getUserQuery } from './user-query.js'

export async function getUser (fastify, opts) {
fastify.get(
'/',
{
preHandler: fastify.auth([fastify.verifyJWT]),
schema: {
response: {
200: userJsonSchema
}
}
},
async function (request, reply) {
const userId = request.user.id

const query = getUserQuery({ userId })

const results = await fastify.pg.query(query)
const user = results.rows.pop()

if (user) {
// TODO refresh token
return user
} else {
reply.statusCode = 404
}
}
)
}
42 changes: 4 additions & 38 deletions routes/api/user/index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,7 @@
import SQL from '@nearform/sql'
import S from 'fluent-json-schema'

const userJsonSchema = S.object()
.prop('id', S.string().format('uuid'))
.prop('email', S.string().format('email'))
.prop('username', S.string())
.prop('email_confirmed', S.boolean())
import { getUser } from './get-user.js'

export default async function userRoutes (fastify, opts) {
fastify.get(
'/',
{
preHandler: fastify.auth([fastify.verifyJWT]),
schema: {
response: {
200: userJsonSchema
}
}
},
async function (request, reply) {
const id = request.user.id

const query = SQL`
SELECT id, email, username, email_confirmed
FROM users
WHERE id = ${id}
`

const results = await fastify.pg.query(query)
const user = results.rows.pop()

if (user) {
// TODO refresh token
return user
} else {
reply.statusCode = 404
}
}
)
await Promise.all([
getUser(fastify, opts)
])
}
7 changes: 7 additions & 0 deletions routes/api/user/user-props.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import S from 'fluent-json-schema'

export const userJsonSchema = S.object()
.prop('id', S.string().format('uuid'))
.prop('email', S.string().format('email'))
.prop('username', S.string())
.prop('email_confirmed', S.boolean())
12 changes: 12 additions & 0 deletions routes/api/user/user-query.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import SQL from '@nearform/sql'

export function getUserQuery ({
userId
}) {
const query = SQL`
select id, email, username, email_confirmed
from users
where id = ${userId}`

return query
}

0 comments on commit 8b16383

Please sign in to comment.