Skip to content
Merged
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
17 changes: 7 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,18 @@ yarn add @secjs/http

## Usage

### Sec
### SecJS

> Use Sec to create the Http server and map all your routes with handlers
> Use SecJS to create the Http server and map all your routes with handlers

```ts
import { Sec, Context } from '@secjs/http'
import { SecJS } from '@secjs/http'
import { SecContextContract } from '@secjs/contracts'

const server = new Sec()
const server = new SecJS()

server.get('/', (ctx: Context) => {
ctx.response.writeHead(200, { 'Content-Type': 'application/json' })

ctx.response.write(JSON.stringify({ hello: 'world!' }))

ctx.response.end()
server.get('/', (ctx: SecContextContract) => {
ctx.response.status(200).json({ hello: 'world!' })
})

server.listen(4040, () => console.log('Server running!'))
Expand Down
6 changes: 3 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from './src/server'
export * from './src/SecJS'

export * from './src/Contracts/RouteContract'
export * from './src/Contracts/HandlerContract'
export * from './src/Context/Request/SecRequest'
export * from './src/Context/Response/SecResponse'
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@secjs/http",
"version": "0.0.5",
"version": "0.0.7",
"description": "",
"scripts": {
"build": "tsc",
Expand All @@ -16,8 +16,8 @@
"author": "João Lenon <lenonsec7@gmail.com>",
"license": "MIT",
"dependencies": {
"@secjs/contracts": "^1.0.7",
"@secjs/utils": "^1.3.0"
"@secjs/contracts": "^1.1.0",
"@secjs/utils": "^1.3.2"
},
"files": [
"src/*.d.ts",
Expand Down
76 changes: 76 additions & 0 deletions src/Context/Request/SecRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { SecRequestContract } from '@secjs/contracts'
import { Route } from '@secjs/utils/src/Classes/Route'

export class SecRequest implements SecRequestContract {
private _ip = ''
private _body = ''
private _method = ''
private _params = {}
private _queries = {}
private _headers = {}
private _fullUrl = ''
private _baseUrl = ''
private _originalUrl = ''
private routeUtils = new Route()

constructor(request: any) {
this._body = request.body
this._method = request.method
this._originalUrl = request.url
this._headers = request.headers
this._baseUrl = request.route.path
this._ip = request.socket.remoteAddress
this._fullUrl = this.routeUtils.removeQueryParams(request.url)
this._queries = this.routeUtils.getQueryParamsValue(request.url) || {}
this._params =
this.routeUtils.getParamsValue(request.route.path, request.url) || {}
}

payload(payload: string, defaultValue?: string): any {
return this.body[payload] || defaultValue
}

param(param: string, defaultValue?: string): string {
return this.params[param] || defaultValue
}

query(query: string, defaultValue?: string): string {
return this.queries[query] || defaultValue
}

header(header: string, defaultValue?: string): string {
return this._headers[header] || defaultValue
}

get ip(): string {
return this._ip
}

get body(): any {
return this._body
}

get params(): any {
return this._params
}

get queries(): any {
return this._queries
}

get method(): string {
return this._method
}

get fullUrl(): string {
return this._fullUrl
}

get baseUrl(): string {
return this._baseUrl
}

get originalUrl(): string {
return this._originalUrl
}
}
55 changes: 55 additions & 0 deletions src/Context/Response/SecResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { ServerResponse } from 'http'
import { SecResponseContract } from '@secjs/contracts'

export class SecResponse implements SecResponseContract {
private vanillaResponse: ServerResponse

constructor(response: ServerResponse) {
this.secResponseBuilder(response)
}

private secResponseBuilder(response: ServerResponse): void {
this.vanillaResponse = response
}

end(): void {
this.vanillaResponse.end()
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
send(data?: any): void {
this.vanillaResponse.end(data)
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
json(data?: any): void {
this.vanillaResponse.setHeader('Accept', 'application/json')
this.vanillaResponse.setHeader('Content-Type', 'application/json')

this.vanillaResponse.end(JSON.stringify(data))
}

status(code: number): this {
this.vanillaResponse.statusCode = code

return this
}

header(header: string, value: any): this {
this.vanillaResponse.setHeader(header, value)

return this
}

safeHeader(header: string, value: any): this {
this.vanillaResponse.setHeader(header, value)

return this
}

removeHeader(header: string): this {
this.vanillaResponse.removeHeader(header)

return this
}
}
11 changes: 0 additions & 11 deletions src/Contracts/HandlerContract.ts

This file was deleted.

10 changes: 0 additions & 10 deletions src/Contracts/RouteContract.ts

This file was deleted.

88 changes: 88 additions & 0 deletions src/SecJS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import constants from './constants'

import { Route } from '@secjs/utils/src/Classes/Route'
import { SecRequest } from './Context/Request/SecRequest'
import { SecResponse } from './Context/Response/SecResponse'
import { createServer, IncomingMessage, Server } from 'http'
import { InternalRouteContract, SecHandlerContract } from '@secjs/contracts'

export class SecJS {
private nodeServer: Server
private routeUtils = new Route()
private routes: InternalRouteContract[] = []

private async getBody(request: IncomingMessage): Promise<any> {
const buffers = []

for await (const chunk of request) {
buffers.push(chunk)
}

if (!buffers.length) return {}

return JSON.parse(Buffer.concat(buffers).toString())
}

private getRoute(url: string, method: string) {
return (
this.routes.find(
route =>
route.matcher.test(this.routeUtils.removeQueryParams(url)) &&
route.method === method,
) || constants.DEFAULT_ROUTE
)
}

private createRouteHandler(
path: string,
method: string,
secHandler: SecHandlerContract,
): void {
this.routes.push({
path,
method: method.toUpperCase(),
handler: secHandler,
params: this.routeUtils.getParamsName(path),
matcher: this.routeUtils.createMatcher(path),
})
}

listen(port?: number, cb?: () => void): void {
this.nodeServer = createServer(async (request: any, response: any) => {
const { url, method } = request

const route = this.getRoute(url, method)

request.route = route
request.body = await this.getBody(request)

return route.handler({
next: () => console.log('next'),
request: new SecRequest(request),
response: new SecResponse(response),
})
})

this.nodeServer.listen(port || constants.PORT, cb)
}

close(cb?: (err?: Error) => void): void {
this.nodeServer.close(cb)
}

get(route: string, secHandler: SecHandlerContract): void {
this.createRouteHandler(route, this.get.name, secHandler)
}

post(route: string, secHandler: SecHandlerContract): void {
this.createRouteHandler(route, this.post.name, secHandler)
}

put(route: string, secHandler: SecHandlerContract): void {
this.createRouteHandler(route, this.put.name, secHandler)
}

delete(route: string, secHandler: SecHandlerContract): void {
this.createRouteHandler(route, this.delete.name, secHandler)
}
}
10 changes: 3 additions & 7 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context } from './Contracts/HandlerContract'
import { SecContextContract } from '@secjs/contracts'

export default {
PORT: 4040,
Expand All @@ -12,12 +12,8 @@ export default {
method: 'ALL',
params: [],
matcher: /\//,
handler: (ctx: Context): any => {
ctx.response.writeHead(404, { 'Content-Type': 'application/json' })

ctx.response.write(JSON.stringify({ message: 'Not found!' }))

ctx.response.end()
handler: ({ response }: SecContextContract): any => {
return response.status(404).json({ message: 'Not found!' })
},
},
}
74 changes: 0 additions & 74 deletions src/server.ts

This file was deleted.

Loading