Skip to content

Commit

Permalink
feat(validator): migrate to @athenna/validator
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed May 11, 2024
1 parent 335d46f commit 705605b
Show file tree
Hide file tree
Showing 14 changed files with 176 additions and 241 deletions.
203 changes: 100 additions & 103 deletions package-lock.json

Large diffs are not rendered by default.

41 changes: 23 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,23 @@
"#tests": "./tests/index.js"
},
"dependencies": {
"@athenna/artisan": "^4.41.0",
"@athenna/common": "^4.36.0",
"@athenna/config": "^4.20.0",
"@athenna/core": "^4.37.0",
"@athenna/database": "^4.49.0",
"@athenna/http": "^4.32.0",
"@athenna/ioc": "^4.19.0",
"@athenna/logger": "^4.20.0",
"@athenna/artisan": "^4.42.0",
"@athenna/common": "^4.39.0",
"@athenna/config": "^4.21.0",
"@athenna/core": "^4.38.0",
"@athenna/database": "^4.50.0",
"@athenna/http": "^4.34.0",
"@athenna/ioc": "^4.20.0",
"@athenna/logger": "^4.21.0",
"@athenna/mail": "^4.18.0",
"@athenna/view": "^4.21.0",
"@athenna/validator": "^4.1.0",
"@athenna/view": "^4.22.0",
"@fastify/cors": "^8.5.0",
"@fastify/helmet": "^11.1.1",
"@fastify/rate-limit": "^8.1.1",
"@fastify/static": "^7.0.1",
"@fastify/swagger": "^8.14.0",
"@fastify/swagger-ui": "^3.0.0",
"@vinejs/vine": "^2.0.0",
"bcrypt": "^5.1.1",
"jsonwebtoken": "^9.0.2",
"knex": "^3.1.0",
Expand Down Expand Up @@ -138,7 +138,6 @@
"athenna": {
"services": [
"#src/helpers/queue",
"#src/helpers/validator",
"#src/services/user.service",
"#src/services/auth.service"
],
Expand All @@ -150,9 +149,9 @@
"@athenna/view/providers/ViewProvider",
"@athenna/mail/providers/MailProvider",
"@athenna/mail/providers/SmtpServerProvider",
"@athenna/view/providers/ViewProvider",
"#src/providers/queueworker.provider",
"#src/providers/validator.provider"
"#src/providers/validator.provider",
"@athenna/validator/providers/ValidatorProvider"
],
"controllers": [
"#src/controllers/user.controller",
Expand Down Expand Up @@ -228,7 +227,8 @@
"path": "@athenna/database/commands/MigrationRevertCommand",
"loadApp": true
},
"make:view": "@athenna/view/commands/MakeViewCommand"
"make:view": "@athenna/view/commands/MakeViewCommand",
"make:validator": "@athenna/validator/commands/MakeValidatorCommand"
},
"templates": {
"exception": "node_modules/@athenna/core/templates/exception.edge",
Expand All @@ -247,7 +247,9 @@
"model": "node_modules/@athenna/database/templates/model.edge",
"seeder": "node_modules/@athenna/database/templates/seeder.edge",
"migration": "node_modules/@athenna/database/templates/migration.edge",
"view": "node_modules/@athenna/view/templates/view.edge"
"view": "node_modules/@athenna/view/templates/view.edge",
"validator-http": "node_modules/@athenna/validator/templates/validator-http.edge",
"validator-console": "node_modules/@athenna/validator/templates/validator-console.edge"
},
"directories": {
"bootstrap": "bin",
Expand All @@ -258,6 +260,7 @@
"providers": "src/providers",
"facades": "src/providers/facades",
"services": "src/services",
"validators": "src/validators",
"commands": "src/commands",
"controllers": "src/controllers",
"middlewares": "src/middlewares",
Expand All @@ -278,11 +281,13 @@
],
"middlewares": [
"#src/middlewares/auth.middleware",
"#src/validators/login.validator",
"#src/validators/register.validator",
"#src/validators/update.validator",
"#src/interceptors/response.interceptor",
"#src/middlewares/pagination.middleware"
],
"validators": [
"#src/validators/login.validator",
"#src/validators/register.validator",
"#src/validators/update.validator"
]
}
}
12 changes: 0 additions & 12 deletions src/exceptions/validation.exception.ts

This file was deleted.

27 changes: 0 additions & 27 deletions src/helpers/validator.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/providers/facades/validator.ts

This file was deleted.

72 changes: 29 additions & 43 deletions src/providers/validator.provider.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { Is } from '@athenna/common'
import { Database } from '@athenna/database'
import { Validate } from '@athenna/validator'
import { ServiceProvider } from '@athenna/ioc'
import { SimpleErrorReporter } from '@vinejs/vine'
import type { FieldContext } from '@vinejs/vine/types'
import { Validator } from '#src/providers/facades/validator'
import { ValidationException } from '#src/exceptions/validation.exception'

type UniqueOptions = {
table: string
Expand All @@ -18,54 +15,43 @@ declare module '@vinejs/vine' {
}
}

export class ErrorReporter extends SimpleErrorReporter {
createError(): any {
return new ValidationException(this.errors)
}
}

export default class ValidatorProvider extends ServiceProvider {
public async boot() {
Validator.schema().errorReporter = () => new ErrorReporter()

Validator.extend(
'unique',
async (value: unknown, options: UniqueOptions, field: FieldContext) => {
/**
* We do not want to deal with non-string
* values. The "string" rule will handle the
* the validation.
*/
if (!Is.String(value)) {
return
}

if (!options.column) {
options.column = field.name as string
}

if (options.max) {
const rows = await Database.table(options.table)
.select(options.column)
.where(options.column, value)
.findMany()

if (rows.length > options.max) {
field.report('The {{ field }} field is not unique', 'unique', field)
}
Validate.extend().string('unique', async (value, options, field) => {
/**
* We do not want to deal with non-string
* values. The "string" rule will handle the
* the validation.
*/
if (!Is.String(value)) {
return
}

return
}
if (!options.column) {
options.column = field.name as string
}

const existsRow = await Database.table(options.table)
if (options.max) {
const rows = await Database.table(options.table)
.select(options.column)
.where(options.column, value)
.exists()
.findMany()

if (existsRow) {
if (rows.length > options.max) {
field.report('The {{ field }} field is not unique', 'unique', field)
}

return
}

const existsRow = await Database.table(options.table)
.select(options.column)
.where(options.column, value)
.exists()

if (existsRow) {
field.report('The {{ field }} field is not unique', 'unique', field)
}
)
})
}
}
10 changes: 3 additions & 7 deletions src/routes/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ Route.group(() => {
Route.group(() => {
Route.get('users', 'UserController.index').middleware('pagination')
Route.get('users/:id', 'UserController.show')
Route.put('users/:id', 'UserController.update').middleware(
'update:validator'
)
Route.put('users/:id', 'UserController.update').validator('user:update')
Route.delete('users/:id', 'UserController.delete')
}).name('users')
}).middleware('auth')
Expand All @@ -26,10 +24,8 @@ Route.group(() => {
'AuthController.confirmEmailPasswordChange'
)

Route.post('login', 'AuthController.login').middleware('login:validator')
Route.post('register', 'AuthController.register').middleware(
'register:validator'
)
Route.post('login', 'AuthController.login').validator('user:login')
Route.post('register', 'AuthController.register').validator('user:register')
})
.prefix('/api/v1')
.interceptor('response')
13 changes: 0 additions & 13 deletions src/validators/base.validator.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/validators/login.validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Middleware, type Context } from '@athenna/http'
import { BaseValidator } from '#src/validators/base.validator'
import { type Context } from '@athenna/http'
import { Validator, BaseValidator } from '@athenna/validator'

@Middleware({ name: 'login:validator' })
@Validator({ name: 'user:login' })
export class LoginValidator extends BaseValidator {
public schema = this.validator.object({
email: this.validator.string().email(),
Expand Down
6 changes: 3 additions & 3 deletions src/validators/register.validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Middleware, type Context } from '@athenna/http'
import { BaseValidator } from '#src/validators/base.validator'
import { type Context } from '@athenna/http'
import { Validator, BaseValidator } from '@athenna/validator'

@Middleware({ name: 'register:validator' })
@Validator({ name: 'user:register' })
export class RegisterValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string(),
Expand Down
6 changes: 3 additions & 3 deletions src/validators/update.validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Middleware, type Context } from '@athenna/http'
import { BaseValidator } from '#src/validators/base.validator'
import { type Context } from '@athenna/http'
import { Validator, BaseValidator } from '@athenna/validator'

@Middleware({ name: 'update:validator' })
@Validator({ name: 'user:update' })
export class UpdateValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string().optional(),
Expand Down
9 changes: 8 additions & 1 deletion storage/queues.json
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
{"default":[],"deadletter":[],"user:email":[],"user:password":[{"user":{"name":"João Lenon","email":"[email protected]"},"password":"$2b$10$utsMOdfjDFKeEdD6UKgXieeGgzh/KtoLPq0Q7il4Qlsvr7/IC23Qi"}],"user:email:password":[],"user:confirm":[]}
{
"default":[],
"deadletter":[],
"user:email":[],
"user:password":[],
"user:email:password":[],
"user:confirm":[]
}
4 changes: 3 additions & 1 deletion tests/e2e/auth.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ export default class AuthControllerTest extends BaseHttpTest {

const queue = await Queue.queue('user:confirm')

console.log(response.response)

assert.deepEqual(await queue.length(), 1)
assert.isTrue(await User.exists({ email: '[email protected]' }))
response.assertStatusCode(201)
Expand Down Expand Up @@ -389,7 +391,7 @@ export default class AuthControllerTest extends BaseHttpTest {
}

@Test()
public async shouldThrowNotFoundExceptionIfTokenDoesNotExistWhenConfirmingPassword({ request }: Context) {
public async shouldThrowNotFoundExceptionIfTokenDoesNotExistWhenConfirmingEmailPassword({ request }: Context) {
const response = await request.get('/api/v1/confirm/email/password', {
query: {
token: 'not-found'
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/user.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export default class UserControllerTest extends BaseHttpTest {
}

@Test()
public async shouldThrowUnauthorizedExceptionWhenTryingToGetAllUsersWithoutAToken({ request }: Context) {
public async shouldThrowUnauthorizedExceptionWhenTryingToGetOneUserWithoutAToken({ request }: Context) {
const response = await request.get('/api/v1/users/1')

response.assertStatusCode(401)
Expand Down

0 comments on commit 705605b

Please sign in to comment.