MongoDB + Golang -> REST API

Um dos métodos que uso para estudar uma linguagem nova é fazer algo que já domino em uma linguagem/tecnologia e que tem alguma aplicação prática, por diversas razões:

  • não preciso pensar num problema imaginário
  • tem alguma aderência com uma necessidade real
  • já sei qual o resultado esperado
  • consigo ter alguma base de comparação

Algumas semanas atrás comecei a olhar muito material sobre Golang e me interessei. Tenho trabalhado faz alguns anos majoritariamente com javascript, tanto no backend quanto no frontend (muito Angular e React e com aquele carinho que todo web developer deveria ter por jQuery, sem falar em ES6…


This is the fifth (and last) post from the series about testing NodeJS API with Jest and Supertest! Now we are ready to test a REST API with some authenticated endpoints!

Create the post.test.js inside test/controllers with the following code, that is the basic:

const request = require('supertest')let appdescribe('Post model Endpoints', () => {
let token
beforeAll(async () => {
app = require('../../app')
const res = await request(app)
.post('/users/signin')
.send({ email: 'fake@fake.com', password: 'fake' })
token = res.body.token
})
afterAll(async () => {
await app.close()
})
})

It is similar to the structure we wrote in the previous…


We have already created our server, the API and set up the test environment. Now it's time to write the first real test: let;'s check if the user's sign in is correct!

Add 2 new tasks to package.json and fix the test:

"scripts": {
"test": "cross-env MONGOURL=mongodb://localhost:27017/nodejs_jestsupertestmongodb_example_test NODE_ENV=test jest --testTimeout=10000",
"migrate:reset": "cross-env NODE_ENV=test MONGOURL=mongodb://localhost:27017/nodejs_jestsupertestmongodb_example_test node ./test/test_migrate.js",
"pretest": "npm run migrate:reset"
}

When we run npm test, the pretest task will be executed. It will set test as NODE_ENV and then run the migrate:reset task. …


Now that we have a server and an API we can set up our test environment/tasks.

Install depencencies

npm i --save-dev cross-env supertest jest
  • Jest: testing framework, with a in-built test runner, assertion library and mocking support(and more)
  • Supertest: library for testing Node.js HTTP servers, enabling to programmatically send HTTP requests
  • cross-env: library that allows to set environment variables in any OS

Now, let's add a test task in the package.json:

"scripts": {
"test": "cross-env NODE_ENV=test jest — testTimeout=10000"
}

If you try to run this task you will have this output:

npm run test > cross-env NODE_ENV=test jest —…

In the second post about testing endpoints from an NodeJS app with Express, I will show how to create basic endpoints for a model (in this example, a blog Post that as a relation with an user) that require authentication — so in the third post we will finally see how to test them! In the first, I have shown how to create an the server with user authentication.

Let’s create a Post model, that will reference the authenticated user. In models/ folder, create Post.js with

const mongoose = require('mongoose') const postSchema = new mongoose.Schema({ title: { type: String, required…

I want to show how I'm testing NodeJS APIs with Jest and Supertest in a series of posts. First of all, in order to test an API, we must to have an API.
So in the part one, I will show how to create a simple API, using Express and MongoDB, that handles user authentication (sign up and in).

Creating a basic Express server

mkdir nodejs-example
cd nodejs-example
npm init
npm i — save mongodb mongoose express
touch app.js

Edit app.js

const express = require('express')
const app = express()
app.set('host', process.env.EXPRESS_HOST || '0.0.0.0')
app.set('port', process.env.EXPRESS_PORT || 8080)
if(process.env.NODE_ENV !== 'test')…


I have been working with frontend development since 2005 (Oh God, time is passing!) and I am always trying the new technologies, for different reasons. And in my current job, at Banco Votorantim, one of our "benefits" and "duties" is to bring new technologies to our stack.

When I first had to build a mobile app, I choose Ionic (it was on its v1); it has been an easy choice for me given the former experience I already had. I have been using Ionic till today (it is in v4 stable, stronger than ever) and I really like it, but…


Ainda bem que anos atrás encontrei a corrida, um esporte que ocupa minha vida, que me ajudou a ser uma pessoa melhor e que me dá prazer praticar (além de ter conhecido pessoas maravilhosas e um mundo bem diferente).
Meio que naturalmente o que começou com corridas leves e curtas cresceu e fazer uma maratona (a distância rainha das corridas de rua) se tornou algo real e parte dos meus planos. Minha idéia é fazer uma por ano, e em 2017 farei minha quarta: Berlin.

Meia-maratona de Porto Alegre 2017, prova usada como treino

Abaixo vou contar como é minha rotina, que é bem parecida com a de diversas…


The new HTTP Client from Angular (4.3), among a lot of new features, has one of the most important (for me): the possibility to intercept all http requests in an easier way and change them, adding some custom header (an usual need for those who use web token auth pattern).

I’m currently using this module below. You can place it in a file called interceptor.module.

import { Injectable, NgModule} from ‘@angular/core’;
import { Observable } from ‘rxjs/Observable’;
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’;

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;

@Injectable() export class HttpsRequestInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>…


No semana passada minha esposa colocou à venda o celular dela (aproveitando o jabá, um Moto G3 16gBytes). Ela desencanou de colocar no Enjoei por causa da taxa de comissão (acho que 20%). Fez o anúncio no Mercado Livre, bonitinho, e em poucas horas veio um contato.

O começo

A pessoa que contactou tinha o nome de Anthony, ele fez algumas perguntas e de cara escreveu algo como:

por favor, me envie uma mensagem no email anthony alguma coisa arroba gM @m 4 il c om para que eu tire algumas dúvidas.

Na vontade de fazermos a venda, contactamos ele (falha nossa…

Christian Benseler

Web development, sports, burgers <3

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store