-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implementa utilização do TypeScript no projeto.
- Loading branch information
Showing
11 changed files
with
3,538 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,26 @@ | ||
'use strict'; | ||
|
||
// Importa a dependência referente ao ExpressJS | ||
var express = require('express'); | ||
// Cria um server baseado no ExpressJS | ||
"use strict"; | ||
var express = require("express"); | ||
var bodyParser = require("body-parser"); | ||
var server = express(); | ||
// Obtém o objeto necessário para criação de rotas | ||
var router = express.Router(); | ||
|
||
// Implementa a rota relativa "/" com o método "GET" | ||
var nomes = []; | ||
router | ||
.route('/') | ||
// @requisicao: O objeto requisição, contém os dados inseridos na requisição, parâmetros, json, arquivos, enfim, | ||
// qualquer coisa enviada ao servidor | ||
// @resposta: A resposta é utilizada para retornar valores ao sistema que chamou o método | ||
// @proximo: Esse parâmetro é um método utilizado para chamar a próxima camada de funções do ExpressJS, por padrão, | ||
// a próxima camada é o tratamento de erro do ExpressJS | ||
.route("/") | ||
.get(bodyParser.json({}), function (requisicao, resposta, proximo) { return resposta.status(200).json(nomes); }); | ||
router | ||
.route("/:nome") | ||
.get(function (requisicao, resposta, proximo) { | ||
// Aqui, nós indicamos que o HTTP Status da resposta será 200, ou seja, OK, e que será enviada a mensagem | ||
// "Hello World" com uma quebra de linha ao final | ||
return resposta.status(200).send('Hello World\n'); | ||
}); | ||
|
||
// Neste ponto, indico ao servidor que quando o cliente chamar a rota absoluta "/hello-world" no endereço | ||
// "localhost:3000/hello-world", a rota criada acima deve ser utilizada | ||
server.use('/hello-world', router); | ||
|
||
// Subo o servidor na porta 3000 | ||
server.listen(3000, function () { | ||
// Ao subir o servidor, exibo as mensagens abaixo no terminal | ||
console.log('Server rodando no endereço http://localhost:3000.'); | ||
console.log('Execute o comando "curl http://localhost:3000/hello-world/" para verificar a mensagem de retorno, ou acesse um ' + | ||
'navegador e entre com o endereço.'); | ||
}); | ||
if (nomes.indexOf(requisicao.params.nome) != -1) { | ||
return proximo(new TypeError("Nome " + requisicao.params.nome + " j\u00E1 cadastrado.")); | ||
} | ||
nomes.unshift(requisicao.params.nome); | ||
resposta.status(200).send("Bem-vindo ao centro Hello World \"" + requisicao.params.nome + "\".\n"); | ||
}); | ||
var port = 3000; | ||
var endpoint = "/hello-world"; | ||
server.use(endpoint, router); | ||
server.listen(port, function () { | ||
var endereco = "http://localhost:3000"; | ||
console.log("Server rodando no endere\u00E7o " + endereco); | ||
console.log("Execute o comando \"curl " + endereco + "/hello-world/\" para verificar a mensagem de retorno, ou acesse um navegador e entre com o endere\u00E7o."); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
"use strict"; | ||
|
||
// Importa a dependência referente ao ExpressJS | ||
import express = require("express"); | ||
import bodyParser = require("body-parser"); | ||
// Cria um server baseado no ExpressJS | ||
var server: express.Application = express(); | ||
// Obtém o objeto necessário para criação de rotas | ||
var router: express.Router = express.Router(); | ||
|
||
var nomes = []; | ||
|
||
// Implementa a rota relativa "/" com o método "GET" | ||
router | ||
.route("/") | ||
// @requisicao: O objeto requisição, contém os dados inseridos na requisição, parâmetros, json, arquivos, enfim, | ||
// qualquer coisa enviada ao servidor | ||
// @resposta: A resposta é utilizada para retornar valores ao sistema que chamou o método | ||
// @proximo: Esse parâmetro é um método utilizado para chamar a próxima camada de funções do ExpressJS, por padrão, | ||
// a próxima camada é o tratamento de erro do ExpressJS | ||
.get( | ||
// Configuro um conversor de JSON nesta rota relativa | ||
bodyParser.json({}), | ||
// Aqui, nós indicamos que o HTTP Status da resposta será 200, ou seja, OK, e que será enviada a mensagem | ||
// "Hello World" com uma quebra de linha ao final | ||
(requisicao: express.Request, resposta: express.Response, proximo: Function) => resposta.status(200).json(nomes)); | ||
|
||
router | ||
.route("/:nome") | ||
.get( | ||
(requisicao: express.Request, resposta: express.Response, proximo: Function) => { | ||
// Caso o nome esteja cadastrado, exibo um erro ao usuário. | ||
if (nomes.indexOf(requisicao.params.nome) != -1) { | ||
// A função próximo utilizada direciona para um captador de erros do NodeJS, onde os mesmos são exibidos | ||
// junto com a callstack tornando mais fácil identificar um bug. | ||
return proximo(new TypeError(`Nome ${requisicao.params.nome} já cadastrado.`)); | ||
} | ||
// Adiciono o nome na lista de nomes. | ||
nomes.unshift(requisicao.params.nome); | ||
resposta.status(200).send(`Bem-vindo ao centro Hello World "${requisicao.params.nome}".\n`); | ||
}); | ||
|
||
// Configurações da rota. | ||
var port: number = 3000; | ||
var endpoint: string = "/hello-world"; | ||
|
||
// Neste ponto, indico ao servidor que quando o cliente chamar a rota absoluta "/hello-world" no endereço | ||
// "localhost:3000/hello-world", a rota criada acima deve ser utilizada | ||
server.use(endpoint, router); | ||
|
||
// Subo o servidor na porta 3000 | ||
server.listen(port, () => { | ||
// Ao subir o servidor, exibo as mensagens abaixo no terminal | ||
var endereco: string = "http://localhost:3000"; | ||
console.log(`Server rodando no endereço ${endereco}`); | ||
console.log(`Execute o comando \"curl ${endereco}/hello-world/\" para verificar a mensagem de retorno, ou acesse um navegador e entre com o endereço.`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
{ | ||
"version": "1.5.0-beta", | ||
"compilerOptions": { | ||
"target": "es5", | ||
"module": "commonjs", | ||
"moduleResolution": "node", | ||
"isolatedModules": false, | ||
"jsx": "react", | ||
"experimentalDecorators": true, | ||
"emitDecoratorMetadata": true, | ||
"declaration": false, | ||
"noImplicitAny": false, | ||
"removeComments": true, | ||
"noLib": false, | ||
"preserveConstEnums": true, | ||
"suppressImplicitAnyIndexErrors": true | ||
}, | ||
"filesGlob": [ | ||
"./**/*.ts", | ||
"./**/*.tsx", | ||
"!./node_modules/**/*" | ||
], | ||
"files": [ | ||
"./app.ts", | ||
"./typings/body-parser/body-parser.d.ts", | ||
"./typings/express/express.d.ts", | ||
"./typings/mime/mime.d.ts", | ||
"./typings/node/node.d.ts", | ||
"./typings/serve-static/serve-static.d.ts", | ||
"./typings/tsd.d.ts" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
{ | ||
"version": "v4", | ||
"repo": "borisyankov/DefinitelyTyped", | ||
"ref": "master", | ||
"path": "typings", | ||
"bundle": "typings/tsd.d.ts", | ||
"installed": { | ||
"express/express.d.ts": { | ||
"commit": "6f6e5c7dd9effe21fee14eb65fe340ecbbc8580a" | ||
}, | ||
"serve-static/serve-static.d.ts": { | ||
"commit": "6f6e5c7dd9effe21fee14eb65fe340ecbbc8580a" | ||
}, | ||
"node/node.d.ts": { | ||
"commit": "6f6e5c7dd9effe21fee14eb65fe340ecbbc8580a" | ||
}, | ||
"mime/mime.d.ts": { | ||
"commit": "6f6e5c7dd9effe21fee14eb65fe340ecbbc8580a" | ||
}, | ||
"body-parser/body-parser.d.ts": { | ||
"commit": "6f6e5c7dd9effe21fee14eb65fe340ecbbc8580a" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
// Type definitions for body-parser | ||
// Project: http://expressjs.com | ||
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/> | ||
// Definitions: https://github.com/borisyankov/DefinitelyTyped | ||
|
||
/// <reference path="../express/express.d.ts" /> | ||
|
||
declare module "body-parser" { | ||
import * as express from "express"; | ||
|
||
/** | ||
* bodyParser: use individual json/urlencoded middlewares | ||
* @deprecated | ||
*/ | ||
|
||
function bodyParser(options?: { | ||
/** | ||
* if deflated bodies will be inflated. (default: true) | ||
*/ | ||
inflate?: boolean; | ||
/** | ||
* maximum request body size. (default: '100kb') | ||
*/ | ||
limit?: any; | ||
/** | ||
* function to verify body content, the parsing can be aborted by throwing an error. | ||
*/ | ||
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; | ||
/** | ||
* only parse objects and arrays. (default: true) | ||
*/ | ||
strict?: boolean; | ||
/** | ||
* passed to JSON.parse(). | ||
*/ | ||
receiver?: (key: string, value: any) => any; | ||
/** | ||
* parse extended syntax with the qs module. (default: true) | ||
*/ | ||
extended?: boolean; | ||
}): express.RequestHandler; | ||
|
||
module bodyParser { | ||
export function json(options?: { | ||
/** | ||
* if deflated bodies will be inflated. (default: true) | ||
*/ | ||
inflate?: boolean; | ||
/** | ||
* maximum request body size. (default: '100kb') | ||
*/ | ||
limit?: any; | ||
/** | ||
* request content-type to parse, passed directly to the type-is library. (default: 'json') | ||
*/ | ||
type?: any; | ||
/** | ||
* function to verify body content, the parsing can be aborted by throwing an error. | ||
*/ | ||
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; | ||
/** | ||
* only parse objects and arrays. (default: true) | ||
*/ | ||
strict?: boolean; | ||
/** | ||
* passed to JSON.parse(). | ||
*/ | ||
receiver?: (key: string, value: any) => any; | ||
}): express.RequestHandler; | ||
|
||
export function raw(options?: { | ||
/** | ||
* if deflated bodies will be inflated. (default: true) | ||
*/ | ||
inflate?: boolean; | ||
/** | ||
* maximum request body size. (default: '100kb') | ||
*/ | ||
limit?: any; | ||
/** | ||
* request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') | ||
*/ | ||
type?: any; | ||
/** | ||
* function to verify body content, the parsing can be aborted by throwing an error. | ||
*/ | ||
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; | ||
}): express.RequestHandler; | ||
|
||
export function text(options?: { | ||
/** | ||
* if deflated bodies will be inflated. (default: true) | ||
*/ | ||
inflate?: boolean; | ||
/** | ||
* maximum request body size. (default: '100kb') | ||
*/ | ||
limit?: any; | ||
/** | ||
* request content-type to parse, passed directly to the type-is library. (default: 'text/plain') | ||
*/ | ||
type?: any; | ||
/** | ||
* function to verify body content, the parsing can be aborted by throwing an error. | ||
*/ | ||
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; | ||
/** | ||
* the default charset to parse as, if not specified in content-type. (default: 'utf-8') | ||
*/ | ||
defaultCharset?: string; | ||
}): express.RequestHandler; | ||
|
||
export function urlencoded(options?: { | ||
/** | ||
* if deflated bodies will be inflated. (default: true) | ||
*/ | ||
inflate?: boolean; | ||
/** | ||
* maximum request body size. (default: '100kb') | ||
*/ | ||
limit?: any; | ||
/** | ||
* request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') | ||
*/ | ||
type?: any; | ||
/** | ||
* function to verify body content, the parsing can be aborted by throwing an error. | ||
*/ | ||
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; | ||
/** | ||
* parse extended syntax with the qs module. (default: true) | ||
*/ | ||
extended?: boolean; | ||
}): express.RequestHandler; | ||
} | ||
|
||
export = bodyParser; | ||
} |
Oops, something went wrong.