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

Agrega codigo necesario por mongoDB setup y spawn en Windows #1353

Merged
merged 55 commits into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
6e28b43
trabajo necesario por mongoDB setup y spawn en Windows
unjust Apr 3, 2023
8c8ca07
Merge branch 'Laboratoria:main' into bq_api_mongodb_e2e_1293
unjust Apr 12, 2023
cc5b37b
cambios a README
unjust Apr 20, 2023
3eeac05
ideas para adiciones GETTING_STARTED
unjust Apr 20, 2023
772d3da
comentando config y e2e tests mejor
unjust Apr 20, 2023
6b1b691
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust Apr 20, 2023
1458f91
Merge branch 'main' of github.com:Laboratoria/bootcamp into bq_api_mo…
unjust Apr 20, 2023
801a18c
mdlint fixes
unjust Apr 20, 2023
1eeef56
separating docker and mongo guides
unjust Apr 21, 2023
683640e
remove mongo deps from package.json
unjust Apr 21, 2023
f354113
clean mongoDB references de proyecto
unjust Apr 21, 2023
c63ac2c
patch for Mongo
unjust Apr 21, 2023
9da33ec
Update projects/04-burger-queen-api/README.md
Apr 21, 2023
945b216
cambios al readme y guia
unjust Apr 21, 2023
12e048a
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust Apr 21, 2023
abe4552
mdlint fixes
unjust Apr 21, 2023
c728593
readd jsonwebtoken dep
unjust Apr 21, 2023
98c0bcb
remove ws from patch
unjust Apr 21, 2023
c6b01ab
patch in the wrong place
unjust Apr 21, 2023
065010d
patch mongoDB created from project not from bootcamp
unjust Apr 21, 2023
8136213
actualizar table of contents
unjust Apr 21, 2023
f8aa6d3
Merge branch 'main' into bq_api_mongodb_e2e_1293
May 2, 2023
dc6a2a8
update guia and remove mongoose refs
unjust May 5, 2023
d55f2d3
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust May 5, 2023
54dd2f4
minor corrections
unjust May 5, 2023
13ee973
rehacer el patch
unjust May 5, 2023
0d44482
corrections
unjust May 5, 2023
c9b0fd1
remove redundant checklist, node driver resource
unjust May 8, 2023
cd0bde9
Update TODO projects/04-burger-queen-api/controller/users.js
May 8, 2023
0832013
mas detalle en TODO comentarios
unjust May 8, 2023
c3308fa
quitar mysql postgres de readme inicial, hacker edition docker
unjust May 8, 2023
7fa2193
apply and remove patch for e2e tests
unjust May 8, 2023
59943a4
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust May 8, 2023
bf4c67c
linter and section for hacker edition
unjust May 8, 2023
fce3433
Apply grammar and spelling suggestions from code review
May 9, 2023
e9fd40b
remove MySQL and add code link for snippet
unjust May 9, 2023
1b9d260
mas correciones de spelling, con uso de extension
unjust May 9, 2023
b3e99e3
Update auth.js
May 9, 2023
692b210
Apply suggestions from code review
May 10, 2023
c2512d8
update pt README
unjust May 10, 2023
07487b4
translations in pt, editions of docker readme
unjust May 10, 2023
63c38bf
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust May 10, 2023
3c6997b
Merge branch 'main' into bq_api_mongodb_e2e_1293
May 10, 2023
298d952
borra parte 1 de docker, es redundante
unjust May 10, 2023
8f7116c
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust May 10, 2023
44a0c78
mdlint fixes
unjust May 11, 2023
6ede552
cambios de connect y TODOs
unjust May 16, 2023
2e9010e
agregamos status de resp en globalSetup errors
unjust May 16, 2023
2795911
Update projects/04-burger-queen-api/guides/GETTING-STARTED-MONGODB.md
May 16, 2023
002d441
Apply suggestions from code review
May 16, 2023
cdf2202
espanol no pt, error response
unjust May 16, 2023
4266076
Merge branch 'bq_api_mongodb_e2e_1293' of github.com:unjust/bootcamp …
unjust May 16, 2023
ecff913
Merge branch 'main' into bq_api_mongodb_e2e_1293
May 17, 2023
a6a78da
Update README.md guides url
unjust May 17, 2023
e5cb2f8
Update README.pt.md url guides y texto duplicado
unjust May 17, 2023
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
10 changes: 10 additions & 0 deletions projects/04-burger-queen-api/connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const config = require('./config');

// eslint-disable-next-line no-unused-vars
const { dbUrl } = config;

async function connect() {
// TODO: Conexión a la Base de Datos
}

module.exports = { connect };
6 changes: 3 additions & 3 deletions projects/04-burger-queen-api/e2e/globalSetup.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ const createTestUser = () => fetchAsAdmin('/users', {
})
.then((resp) => {
if (resp.status !== 200) {
throw new Error('Could not create test user');
throw new Error(`Response ${resp.status} - Could not create test user`);
unjust marked this conversation as resolved.
Show resolved Hide resolved
}
return fetch('/auth', { method: 'POST', body: __e2e.testUserCredentials });
})
.then((resp) => {
if (resp.status !== 200) {
throw new Error('Could not authenticate test user');
throw new Error(`Response ${resp.status} - Could not authenticate test user`);
}
return resp.json();
})
Expand All @@ -79,7 +79,7 @@ const checkAdminCredentials = () => fetch('/auth', {
})
.then((resp) => {
if (resp.status !== 200) {
throw new Error('Could not authenticate as admin user');
throw new Error(`Response ${resp.status} - Could not authenticate as admin user`);
}

return resp.json();
Expand Down
38 changes: 22 additions & 16 deletions projects/04-burger-queen-api/guides/GETTING-STARTED-MONGODB.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,11 @@ o tu instalación en particular, para ejemplos en cómo levantarlo.
Ahora que ya tenemos un servidor de base de datos, vamos a necesitar elegir un
módulo o librería diseñado para interactuar con nuestra base de datos desde
Node.js. Existen un montón de opciones, pero para este proyecto te recomendamos
usar el [Node driver de MongoDB](https://www.mongodb.com/docs/drivers/node/current/)
usar el [Node.js driver de MongoDB](https://www.mongodb.com/docs/drivers/node/current/)
que es la forma más directa de interactuar con tu instancia de MongoDB.

Hay que instalar el Node Driver en este proyecto usando `npm`.
Hay que instalar el Node.js Driver en este proyecto usando `npm`,
[revisa los docs por más info](https://www.mongodb.com/docs/drivers/node/current/quick-start/download-and-install/#install-the-node.js-driver).
unjust marked this conversation as resolved.
Show resolved Hide resolved

El _boilerplate_ ya incluye un archivo `config.js` donde se leen las
variables de entorno, y entre ellas está `DB_URL`. Como vemos ese valor lo
Expand All @@ -91,17 +92,15 @@ const config = require("./config");

const client = new MongoClient(config.dbUrl);

async function run() {
async function connect() {
try {
await client.connect();
const db = client.db('test');
// ...
} finally {
// Close the database connection when finished or an error occurs
await client.close();
const db = client.db(<NOMBRE_DB>); // Reemplaza <NOMBRE_DB> por el nombre del db
return db;
} catch (error) {
//
}
}
run().catch(console.error);
```

Puedes encontrar mas ejemplos en [la documentación de MongoDB](https://www.mongodb.com/docs/drivers/node/current/).
Expand Down Expand Up @@ -129,18 +128,19 @@ Aquí te guiamos un poco sobre esto TODO's.

### TODO 1: Conectar a la base de datos

En el `index.js` donde arrancamos express y el API, hay:
En el `connect.js` hay que conectar al base de datos.
unjust marked this conversation as resolved.
Show resolved Hide resolved

```js
const { port, dbUrl, secret } = config;
const app = express();
const { dbUrl } = config;

// TODO: Conexión a la Base de Datos
async function connect() {
// TODO: Conexión a la Base de Datos
}
```

Aquí debes usar el `dbUrl` que importamos del config para establecer la conexión,
quizá a través de una función que defines en un modulo y luego importas desde
el index.
Aquí debes usar el `dbUrl` que importamos del config para establecer la conexión.
Las funciones que van a interactuar con la base de datos tienen que invocar
`connect`.

### TODO 2: Crear el usuario _admin_

Expand Down Expand Up @@ -213,6 +213,12 @@ users de la colección en tu base de datos.
Revisa [el tutorial de Node y express en Mozilla](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes)
que habla de controllers.

### TODO 6: Implementar a rota POST `/users`
unjust marked this conversation as resolved.
Show resolved Hide resolved

Os testes e2e invocam a rota POST /users para adicionar a usuária aos testes.
Portanto, antes de poder executar os testes e2e, essa rota deve funcionar
corretamente.

unjust marked this conversation as resolved.
Show resolved Hide resolved
## 6. Definir estrategia de pruebas unitarias

Además de las pruebas `e2e` que ya incluye el _boilerplate_ del proyecto, se
Expand Down
33 changes: 15 additions & 18 deletions projects/04-burger-queen-api/guides/GETTING-STARTED-MONGODB.pt.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,11 @@ iniciar o servidor.
Agora que já temos um servidor de banco de dados, precisamos escolher
um módulo ou biblioteca projetado para interagir com nosso banco de dados
a partir do Node.js. Existem muitas opções, mas para este projeto,
recomendamos o uso do [Node driver do MongoDB](https://www.mongodb.com/docs/drivers/node/current/)
recomendamos o uso do [Node.js driver do MongoDB](https://www.mongodb.com/docs/drivers/node/current/)
que é a forma mais direta de interagir com sua instância do MongoDB.

É necessário instalar o Node Driver neste projeto usando o `npm`.
É necessário instalar o Node.js Driver neste projeto usando o `npm`,
[verifique os documentos para mais informações](https://www.mongodb.com/docs/drivers/node/current/quick-start/download-and-install/#install-the-node.js-driver).

O _boilerplate_ já inclui um arquivo config.js onde as variáveis
de ambiente são lidas, e uma delas é DB_URL. Conforme podemos ver,
Expand All @@ -87,19 +88,15 @@ o cliente escolhido.
const { MongoClient } = require('mongodb');
const config = require("./config");

const client = new MongoClient(config.dbUrl);

async function run() {
async function connect() {
try {
await client.connect();
const db = client.db('test');
// ...
} finally {
// Close the database connection when finished or an error occurs
await client.close();
const db = client.db(<NOMBRE_DB>); // Reemplaza <NOMBRE_DB> por el nombre del db
return db;
} catch (error) {
//
}
}
run().catch(console.error);
```

Você pode encontrar mais exemplos
Expand Down Expand Up @@ -127,18 +124,18 @@ Aqui vamos orientá-lo um pouco sobre esses TODOs.

### TODO 1: Conectar a la base de datos

No arquivo `index.js` onde iniciamos o Express e a API, há:
No arquivo `connect.js`, é necessário conectar ao banco de dados..

```js
const { port, dbUrl, secret } = config;
const app = express();
const { dbUrl } = config;

// TODO: Conexión a la Base de Datos
async function connect() {
// TODO: Conexão com o Banco de Dados
}
```

Aqui você deve usar o `dbUrl` que importamos do arquivo de configuração
para estabelecer a conexão, talvez através de uma função que você define
em um módulo e depois importa no index.
Aqui você deve usar o `dbUrl` que importamos do config para estabelecer a conexão.
As funções que vão interagir com o banco de dados devem invocar o `connect`.

### TODO 2: Criar o usuário _admin_

Expand Down
4 changes: 1 addition & 3 deletions projects/04-burger-queen-api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ const errorHandler = require('./middleware/error');
const routes = require('./routes');
const pkg = require('./package.json');

const { port, dbUrl, secret } = config;
const { port, secret } = config;
const app = express();

// TODO: Conexión a la Base de Datos

app.set('config', config);
app.set('pkg', pkg);

Expand Down
2 changes: 2 additions & 0 deletions projects/04-burger-queen-api/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ module.exports = (app, next) => {
* @code {403} si ya existe usuaria con ese `email`
*/
app.post('/users', requireAdmin, (req, resp, next) => {
// TODO: implementar la ruta para agregar
// nuevos usuarios
});

/**
Expand Down