diff --git a/node/Order.js b/node/Order.js new file mode 100644 index 0000000..34a1881 --- /dev/null +++ b/node/Order.js @@ -0,0 +1,25 @@ +const Order = (() => { + const fs = require('fs'); + + this.save = (order) => { + let orders = require('../orders.json'); + order.id = orders.length ? orders.length + 1 : 1; + orders.push(order); + fs.writeFile('../orders.json', JSON.stringify(orders), { flag: 'w'}); + return order; + }; + + this.getAll = () => { + return require('../orders.json'); + }; + + return { + save : this.save, + getAll : this.getAll + } +})(); + + + +module.exports = Order; + diff --git a/node/index.js b/node/index.js index e69de29..78bd017 100644 --- a/node/index.js +++ b/node/index.js @@ -0,0 +1,54 @@ +const express = require('express'), + bodyParser = require('body-parser'), + request = require('request-promise'), + Order = require('./Order'), + moment = require('moment'), + app = express(); + +const urlAPI = 'https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)'; +const queryString = { + '@dataCotacao' : "'07-20-2018'", + '$top' : '100', + '$format': 'json' +}; +const dollarPrice = request.get({ url: urlAPI, qs: queryString, json: true }); + +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({extended: true})); + +app.get('/api/brl-usd', (req, res) => { + dollarPrice.then((price) => { + res.json({ + 'brl' : 1, + 'usd' : price.value[0].cotacaoVenda.toFixed(2) + }); + }, () => { + res.json({}); + }); +}); + +app.post('/api/orders', (req, res) => { + dollarPrice.then((price) => { + let items = req.body.items || [0]; + let total = items.reduce((a, b) => Number(a) + Number(b), 0); + let totalSellPrice = price.value[0].cotacaoVenda * total; + let order = { + 'created_at' : moment().format("YYYY-MM-DD HH:mm:ss"), + 'total_brl' : total.toFixed(2), + 'total_usd' : totalSellPrice.toFixed(2) + }; + + order = Order.save(order); + res.json(order); + }, () => { + res.json({}); + }); +}); + +app.get('/api/orders', (req, res) => { + res.json(Order.getAll()); +}); + +app.listen(3000, () => { + console.log('Server load'); +}); \ No newline at end of file diff --git a/node/package.json b/node/package.json new file mode 100644 index 0000000..bf7fcaf --- /dev/null +++ b/node/package.json @@ -0,0 +1,17 @@ +{ + "name": "nodePHPTest", + "version": "0.0.0", + "private": true, + "dependencies": { + "body-parser": "^1.0.0", + "compression": "^1.6.1", + "express": ">4.2.0", + "express-load": "^1.1.15", + "express-session": "^1.13.0", + "forever-monitor": "^1.7.0", + "method-override": "^2.3.5", + "moment": "^2.22.2", + "request": "^2.88.0", + "request-promise": "^4.2.2" + } +} diff --git a/php/brl-usd.php b/php/brl-usd.php index e69de29..00afca2 100644 --- a/php/brl-usd.php +++ b/php/brl-usd.php @@ -0,0 +1,21 @@ +get('/', function() use ($app) { + $price = BRLExchange::getDollarPrice(); + + if(!empty($price->value)) { + return $app->json([ + 'brl' => 1, + 'usd' => (float) number_format($price->value[0]->cotacaoVenda, 2, '.', '') + ]); + } + else { + return $app->json([]); + } +}); + +$app->run(); \ No newline at end of file diff --git a/php/composer.json b/php/composer.json new file mode 100644 index 0000000..a3c0f52 --- /dev/null +++ b/php/composer.json @@ -0,0 +1,13 @@ +{ + "require": { + "silex/silex": "^2.2", + "guzzlehttp/guzzle": "^6.3" + }, + "autoload": { + "psr-4" : { + "NodePHPTest\\" : [ + "src/" + ] + } + } +} diff --git a/php/orders.php b/php/orders.php index e69de29..f9c0bd9 100644 --- a/php/orders.php +++ b/php/orders.php @@ -0,0 +1,30 @@ +post('/', function(Request $request) use ($app) { + $price = BRLExchange::getDollarPrice(); + $items = $request->get('items'); + $total = number_format(array_sum($items), 2, '.', ''); + $totalSellPrice = number_format($total * $price->value[0]->cotacaoVenda, 2, '.',''); + + $order = [ + 'created_at' => date('Y-m-d H:i:s'), + 'total_brl' => (float)$total, + 'total_usd' => (float)$totalSellPrice + ]; + + Order::save($order); + return $app->json($order); +}); + +$app->get('/', function() use ($app) { + $orders = Order::getAll(); + return $app->json($orders); +}); + +$app->run(); \ No newline at end of file diff --git a/php/src/BRLExchange.php b/php/src/BRLExchange.php new file mode 100644 index 0000000..4ce15e3 --- /dev/null +++ b/php/src/BRLExchange.php @@ -0,0 +1,26 @@ +request('GET', SELF::$urlAPI, [ + 'query' => [ + '@dataCotacao' => "'07-20-2018'", + '$top' => '100', + '$format' => 'json' + ] + ]); + + $price = json_decode($response->getBody()->getContents()); + return $price; + } + catch(\Exception $e) { + die(); + } + } +} \ No newline at end of file diff --git a/php/src/Order.php b/php/src/Order.php new file mode 100644 index 0000000..48c9452 --- /dev/null +++ b/php/src/Order.php @@ -0,0 +1,35 @@ + { return this[this.length - 1]; }; // Teste/Exemplos const array1 = [1,2,3,4,5,6,7,8,9] @@ -157,7 +157,18 @@ function login($username, $password) { ``` ```php -// Resposta +function login($username, $password) { + $sql = " + select * + from users + where username = :username AND password = :password + "; + + $p_sql = $pdo->prepare($sql); + $p_sql->execute([':username' => $username, ':password' => $password]); + return $p_sql->fetch(PDO::FETCH_ASSOC); +} + ``` --- @@ -240,4 +251,4 @@ Content-Type: applicaton/json "totalBRL": 1650, "totalUSD": 435.84 }] -``` \ No newline at end of file +``` diff --git a/pull_request_template.md b/pull_request_template.md index c09ac93..a45d84d 100644 --- a/pull_request_template.md +++ b/pull_request_template.md @@ -1,5 +1,5 @@ # Node -Versão escolhida: 6.x | 8.x +Versão escolhida: 8.11 # PHP -Versão escolhida: 5.4 | 5.5 | 5.6 | 5.7 | 7.0 | 7.1 | 7.2 \ No newline at end of file +Versão escolhida: 5.6 diff --git a/teorico.md b/teorico.md index 8900235..549d135 100644 --- a/teorico.md +++ b/teorico.md @@ -2,33 +2,35 @@ 1\) Qual a diferença do operador `==` para o operador `===` em JavaScript? -[Resposta] +O operador '===' além de verificar se os valores são iguais, ele também verifica se são do mesmo tipo, já o operador '==' apenas verificas se os valores são iguais, sem considerar a tipagem. + 1.1) Dê 2 exemplos de quando os operadores produziriam resultados diferentes -```js -// Resposta -``` +'1' == 1; // true +'1' === 1; // false +undefined == false; // true +undefined === false; // false --- 2\) Qual recurso javascript é mais recomendado para tratar chamadas asíncronas? -[Resposta] +O recurso mais recomendado para tratar chamadas assíncronas são as Promises. 2.1) Justifique -[Resposta] +Com o uso das Promises, é possível controlar o fluxo de execução do código javascript, permitindo decidir o que será retornado caso uma Promise seja aceita ou rejeitada executar o callback correto através do método then() da Promise que pode inclusive ser encadeado a outros métodos then(). --- 3\) Existem threads em Node? -[Resposta] +Node é single thread. 3.1) Explique -[Resposta] +Node trabalha com single thread não bloqueante e executa funções de maneiras assíncronas através de um event-loop que recebe todas as requisições. Porém é possível destribuir essas requisições para novos processos através do uso de clusterização. --- @@ -51,7 +53,7 @@ getUserByName('jonh doe') .then(user => console.log(user)) ``` -[Resposta] +Resultado: undefined 4.2) ```js @@ -76,9 +78,7 @@ getData() }) ``` -``` -[Resposta] -``` +Resultado : second --- @@ -86,29 +86,35 @@ getData() 1\) Qual a diferença do operador `==` para o operador `===` em PHP? -[Resposta] +O operador '===' além de verificar se os valores são iguais, ele também verifica se são do mesmo tipo, já o operador '==' apenas verificas se os valores são iguais, sem considerar a tipagem. + 1.1) Dê 2 exemplos de quando os operadores produziriam resultados diferentes -```php -// Resposta +``` +$a = '1'; +$a == 1; // true +$a === 1; // false +$a == true; // true +$a === true; // false + ``` --- 2\) Qual a função do apache ou nginx em uma aplicação PHP? -[Resposta] +A função do apache / nginx é criar um servidor web para receber as requisições HTTP, buscar os arquivos necessários e / ou executar scripts PHP e devolver o html ao cliente. --- 3\) Existem threads em PHP? -[Resposta] +Sim, PHP é uma linguagem multi thread. 3.1) Explique -[Resposta] +PHP suporta processamento em paralelo através do uso da extensão pthreads. --- @@ -123,10 +129,10 @@ class Test { echo Test::prop; ``` -[Resposta] +1337 4.2) -```js +```php class A { public static function foo() { return 'bar'; @@ -146,4 +152,4 @@ class B extends A { B::test(); ``` -[Resposta] \ No newline at end of file +'bar'