Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor vertically #20

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { redisConfig, serverConfig } from './config'
import { errorHandler, sessionStore } from './lib/express'
import logger from './lib/log'
import pdfRouter from './pdf-processing/handler'
import userRouter from './users/handler'
import userRouter from './features/users/router'

const app = express()

Expand Down
14 changes: 14 additions & 0 deletions server/src/entities/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import * as z from 'zod'

const userSchema = z.object({
id: z.string().uuid(),
firstName: z.string(),
lastName: z.string(),
email: z.string().email(),
password: z.string().min(5),
pdfs: z.array(z.object({ id: z.string(), fileName: z.string() })).min(1)
})

type User = z.infer<typeof userSchema>

export { User }
38 changes: 38 additions & 0 deletions server/src/features/users/create/createUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Request, Response } from 'express'

import * as z from 'zod'
import { createError } from '../../../lib/error'
import { createUser, userExists } from './data'

const userRequest = z.object({
firstName: z.string(),
lastName: z.string(),
email: z.string().email(),
password: z.string().min(5)
})

const errors = {
validationError: {
name: 'ValidationError',
code: 400,
msg: 'Invalid input',
retryable: false
},
emailConflictError: {
name: 'EmailConflictError',
code: 409,
msg: 'Email already exists',
retryable: false
}
}

const create = async (req: Request, res: Response) => {
const request = await userRequest.parseAsync(req.body).catch((err) => createError(errors.validationError, err))

if (await userExists(request.email)) createError(errors.emailConflictError)

await createUser(request)
res.json({ result: 'ok' })
}

export { create }
48 changes: 48 additions & 0 deletions server/src/features/users/create/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import bcrypt from 'bcrypt'
import * as uuid from 'uuid'
import { User } from '../../../entities/user'
import r, { idx, key, userKey } from '../../../lib/redis'

const handleCreateIdxError = (err: Error) => {
if (err.message.toLowerCase().includes('index already exists')) return

throw err
}

const userExists = async (email: string) => r.sismember(key('emails'), email)

const createIdx = async (userId: string) => {
await r
.send_command(
'FT.CREATE',
idx(userId),
'ON',
'HASH',
'PREFIX',
'1',
key(`pdfs:${userId}`),
'SCHEMA',
'content',
'TEXT',
'PHONETIC',
'dm:en'
)
.catch(handleCreateIdxError)
}

const createUser = async (userReq: Partial<User>) => {
const saltRounds = 8
const password = await bcrypt.hash(userReq.password, saltRounds)

const newUser = { ...userReq, id: uuid.v4(), password } as User

await createIdx(newUser.id)
await r
.multi([
['call', 'JSON.SET', userKey(newUser.id), '.', JSON.stringify(newUser)],
['sadd', key('emails'), newUser.email],
['hmset', idx('email'), newUser.email, newUser.id]
])
.exec()
}
export { createUser, userExists }
11 changes: 11 additions & 0 deletions server/src/features/users/get/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import r, { userKey } from '../../../lib/redis'
import { User } from '../../../entities/user'

const getUser = async (userId: string) => {
const resp = (await r.send_command('JSON.GET', userKey(userId))) as User
const { password, ...payload } = resp

return payload
}

export { getUser }
30 changes: 30 additions & 0 deletions server/src/features/users/get/getUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Request, Response } from 'express'
import { getUser } from './data'
import * as z from 'zod'
import { createError } from '../../../lib/error'

const response = z.object({
firstName: z.string(),
lastName: z.string(),
email: z.string().email(),
pdfs: z.array(z.object({ id: z.string(), fileName: z.string() })).min(1)
})

const errors = {
validationError: {
name: 'InteralServerError',
code: 500,
msg: 'Invalid data',
retryable: false
}
}

const getCurrentUser = async (req: Request, res: Response) => {
const user = await getUser(req.session.userId)

const result = await response.parseAsync(user).catch((err) => createError(errors.validationError, err))

res.json({ result })
}

export { getCurrentUser }
Empty file.
12 changes: 12 additions & 0 deletions server/src/features/users/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { create } from './create/createUser'
import express, { Router } from 'express'

import { auth, safeRouteHandler } from '../../lib/express'
import { getCurrentUser } from './get/getUser'

const router = Router()

router.post('/users', express.json(), safeRouteHandler(create))
router.get('/me', auth, safeRouteHandler(getCurrentUser))

export default router
7 changes: 1 addition & 6 deletions server/src/pdf-processing/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,7 @@ const getParagraphs = (sentences: string[]) => {
const words = sentence.trim().split(' ')

if (words.length + paragraph.length > MAX_PARAGRAPH_SIZE) {
paragraphs.push(
paragraph
.join(' ')
.slice(0)
.trim()
)
paragraphs.push(paragraph.join(' ').slice(0).trim())
console.log(paragraph.length)
paragraph = []
}
Expand Down
20 changes: 0 additions & 20 deletions server/src/users/errors.ts

This file was deleted.

52 changes: 0 additions & 52 deletions server/src/users/handler.ts

This file was deleted.

73 changes: 0 additions & 73 deletions server/src/users/service.ts

This file was deleted.

25 changes: 0 additions & 25 deletions server/src/users/types.ts

This file was deleted.