fabiochiu/medium-articles huggingface dataset:
Backend Perspective of a Frontend Developer — Creation of a Full-Stack Offline Messaging App
By: Berk Akgün
Tags: Nestjs, Full Stack, Nest, Backend, Front End Development

Nest uses almost the same structure with Angular, so if you are familiar with Angular you will get the idea much quicker. In nest, you have modules uses the same design pattern with Angular, DI, dependency injection. You will be creating modules, services, and controllers for your endpoints and implementation logic and import it other modules. So, be careful where you import your modules unless you want to get caught by Circular Dependency Error. To understand more about nest structure, you can check the details in documentation. However, to be more clear and time efficient I will directly start to implement authentication logic explained in the docs of Nest.

npm install --save @nestjs/passport passport passport-local

npm install --save-dev @types/passport-local

npm install --save @nestjs/jwt passport-jwt

npm install --save-dev @types/passport-jwt

npm install --save bcrypt @types/bcrypt

After adding necessary packages, we will create two modules namely, auth and users.

nest g mo auth && nest g co auth && nest g s auth

nest g mo users && nest g co users && nest g s users

For authentication, there will be two authentication strategies in our auth module namely “local” and “JWT” strategy. After some research and analysis, I came up with an idea for authentication. Since JWT will be used in most of the endpoints, all but signup and login endpoints, I will create a jwt-auth-guard for the all application and i will exclude only sign-up and login endpoints by adding is_Public metadata which SetMetadata method Nest provides for us. To be handy, I will create “@Public” and “@UseLocalStrategy” custom decorators to use in signup and login controllers.

Custom Decorators

Strategies can be added to the application like below.

In this strategy, validate is used as default method for validating in nest. After validating, bcrypt service is used for encryption of the password.

And here is the auth-guard which extends jwt auth-guard and let requests with isPublic metadata to pass and force others to jwt authorization for us.I leave it to import these strategies and auth-guard to the app.module for you. To note here, you may want to use validating with email rather than username in local strategy. It uses username by default in PassportStrategy. However, you can change userNameField as whatever field you want to use in super().

Here is our authentication mechanism for our nest application. We also need to fill user module and auth module and controller for testing. To be clear and short, you can take a look at user module and DTOs etc. from github repository will be shared at the bottom of the story. User module consists db services we need for validation of our users. You can see how easy to define an endpoint with nest auth.controller in gist below.
Ruby 裡的陣列與範圍
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
RabbitMQ — 訊息的如何插隊？(Priority). 雖然我們的一般的狀況下我們都希望訊息能夠按照順序被處理，…
Tags: Message Queue, Backend, Message Broker, Rabbitmq, Mq

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
MongoDB vs SQL: the View on the Question from 4 Sides
By: Denis Shilov
Tags: Relational Databases, Backend, Data, Mongodb, MySQL

1. Back-end

Readability

NoSQL is human-readable. If you see some complex SQL query, then you should sit and wait until you finally get what it does. In case of huge queries on dozens of lines, this starts to be insanely long. +3 to MongoDB

Debugging

NoSQL is developer-friendly and is easy to debug. If you write some complex query on SQL, then there is no way to debug it as easily as it is done using MongoDB when you get some strange error. But if you don’t have many JOIN operations, then it is not such hard to debug.

+2 to MongoDB

The complexity of databases and normalization

The question of the presence of many JOIN operations gets us to the problem “to normalize or not to normalize”. If your tables are too normalized, then there are many JOIN operations, which costs too much and cannot be debugged in an easy way.

Normalization typically decreases the size of the database It is WAY HARD to debug normalized database, as there are many JOIN operations JOIN operations cost a lot in terms of performance, that is why normalization is not so good sometimes

There is a special term called denormalization: reduction of the database to making I/O operations quicker by adding some extra data to tables.

I would prefer the compromise and medium normalization in the case of SQL, which also leads to increased debugging latency.

The same problem could happen with Mongo, as its documents are stored in collections. To request some additional information, we should request another collection. But typically developers use normalized collections in the case of Mongo.

So it is just 0

Vulnerabilities

NoSQL does not allow SQL Injections to pass, and SQL Injections are very, very dangerous: it is one of the most popular answers on “Why is my website cracked”.

Let me give an example: you have a search field on your side. When a user types something there, then you get the contents of this input and send it to the server, where the following SQL query is executed:

const query = `SELECT * FROM database WHERE name=${input};`;

Now imagine that the “input” is the following one:

const input = "'; DELETE * FROM database"

Do you see? Your database is now void!

NoSQL does not allow it to happen, as it just does not have such a problem of queries. You don’t have to check if the user wants to drop your database each time you execute a query. +3 to MongoDB

Implementing new features

It is hard to implement new features and change types and schemes of data on SQL. You should do migration, then perform migration tests, which is a lot of headache.

Using MongoDB you can do it without any problem, as it does not require even writing migrations.

3 to MongoDB
Database Constraints, But Why?
Tags: Data Integrity, Database, Rails, Backend, Software Engineering

The Solution: Database Constraints!

Database constraints are the perfect answer to the problem stated above. They also help protect our data in the event that we switch out part of our stack, specifically the backend application that interacts with the database (So many things can go wrong when we make big changes!).

Like model validations, database constraints allow us to declare what the data in a column should look like: does it follow a pattern? Should it be a certain length? Can it be empty? Is there a range of values it should fall within? What about uniqueness? And on and on. In the event that someone bypasses the model validations to add or modify data, that new data won’t be added unless it conforms to the database constraints, thus protecting the integrity of our data.

As a general rule, I like to ensure that my database constraints mirror my model validations, or vice versa. At times, this means I need to break out my old SQL friend when I’m writing migrations, since the out-of-the-box constraints (aka helpers) are limited regardless of what we’re using for the backend application.
Desenvolvedor web: qual a diferença entre front-end, back-end e full-stack?
By: Raísa Boing
Tags: Tecnologia, Full Stack, Web Development, Backend, Front End Development

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Django 101: Run Django Website in 5 simple steps.
By: Gaurav Chaudhary
Tags: Web Development, Backend, Django, Python, Django Framework

This blog is for people who are just beginners in Django but it can also be useful for the developers who have experience in Django but they have to waste time in searching about basic commands when they start some new project after a long break. Just bookmark this article and you are good to go.

What is Django?

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. -according to Django official website

In simple words, Django is a free and open-source framework written in Python. It helps you to develop websites which are secure and it Django is faster and easier.

Enough talk, let’s run our Django website in 5 simple steps:

For Linux users:

Step 1: Make Virtual Environment, also called virtualenv.

Why?

Virtualenv will isolate your Python/Django project. This means that if you need certain libraries or the certain version of those libraries for one project then it will not affect your other projects. It’s like a shield, cool, right.

How?

Open the terminal and go to the directory in which you want to make you virtualenv, for our example we can make a directory by the name djangotest. This directory is just the name of the container for the whole project, its name doesn’t matter, we can rename it whenever we want, it won’t affect the project.

We can create a vurtualenv on Linux by running below command in terminal:

$ python3 -m venv venvtest

Here, venvtest is the name of your virtual environment.

Step 2: Activate your virtual environment.

To activate virtual environment, run below command:

$ source venvtest/bin/activate

You will know that you have virtualenv started when you see that the prompt in your console is prefixed with (venvtest).

Step 3: Installing Django.

Before we do that, we should update pip, the software that we use to install Django:

(venvtest) $ python -m pip install --upgrade pip

Now, install Django:

(venvtest) $ pip install Django

It’ll install the latest version of Django.

Step 4: Starting Django Project.

Write this command to start the project

(venvtest) $ django-admin startproject djangotest .

Here djangotest is the name of the project.

The file structure of the project.

After the previous command, our parent directory will look like this.

Step 5: Starting the Web Server.

Go to the directory that contains the manage.py file. In the console, we can start the webserver by running below command:
How to Install Plugins Manually on WordPress
Tags: Wordpress Web Development, Programming, Wordpress Plugins, Backend, WordPress

Installing plugins from the WordPress Dashboard is so easy that you probably never need to know how to manually install a plugin via FTP. But this method is still useful to know if the WordPress plugin directory is defective or not available.

Steps to install a plugin

Go to the Plugins page on the WordPress Plugin Directory website. Click the red download button to transfer the plugin zip file to your computer Unzip the downloaded plugin files.

All plugins that have been downloaded from the plugins directory are usually in .zip format. Most operating systems (eg Mac, Microsoft Windows, Ubuntu, etc.) have installed software that helps to open zip files. After unzipping the file, extract the folder and place it in a convenient and easily accessible location on your computer. Connect to your site using FTP.

If you have problems with the FTP server, then you can contact us. We provide assistance and help with your FTP connection. From the root directory, navigate to the wp-content folder.

The location of your WordPress installation may differ from each hosting provider. Make sure you know the location before continuing. Go to the /wp-content/plugins directory.

First access wp-content. In this folder there are directories of plugins and themes for your site. Access the plugins folder. This folder contains all the plugins. Upload the plugins folder to the /wp-content/plugins directory on your web server.

Your plugin folder that you want to upload must be named as well as the name of the plugin (for example, if you upload the Gallery plugin, the folder will be /gallery) and contain all the files for that plugin.

Go to the Dashboard Plugins page and you will see the new plugin installed. If an error occurs, delete all recently uploaded files and start over.

Originally published at https://www.mivocloud.com.
Django ORM 模型層 OneToOne(一對一)
By: 承諺 Harry Tsai
Tags: Backend, Orm, Django, One To One

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Create a simple Django Backend App in 5 Steps
By: No One Knows I M A Geek
Tags: Backend, Web Development, Django, Python

Step 1: Install Django and create our first app

In the first step, we will create a virtual environment and install Django in it. Using virtual environments is a good practice since it creates an isolated environment for your project. If you have another project with different dependencies, you can simple create another virtual environment for it. This saves a lot of trouble with dependencies.

After the virtual environment is created and activated, and the Django package has been installed, go on and create a project and an app in the project. A project is a collection of configuration and apps for a particular website.

In this example, we name our project “awesome_project” and create an app “hello” in it.

# Create and activate a virtual environment

virtualenv -p python3 venv

source venv/bin/activate # Install Django

pip install Django # Create a project

django-admin startproject awesome_project

cd awesome_project # Create an app named "hello"

python manage.py startapp hello

cd hello

Step 2: Define a view function

Now that we’ve created a project and an app, we will define a view function that will be called when a request is sent to a certain url. So go on and add the following code in hello/views.py. The “hello” function simply returns a response with the message “Hello! This is awesome!”

# in hello/views.py from django.http import HttpResponse def hello(request):

return HttpResponse("Hello! This is awesome!")

Step 3: Define url routes

Now it’s time to define the endpoint that will call the function we created in step 2. To do this, we need to define an url in hello/urls.py and register it in awesome_project/urls.py.

In awesome_project/urls.py:

from django.urls import include, path urlpatterns = [

path('hello/', include('hello.urls')),

]

In hello/urls.py:

from django.urls import path

from . import views urlpatterns = [

path('', views.hello, name='hello'),

]

Step 4: Register the app

Finally, we need to register the app. It is as simple as adding “hello” to the list of installed apps.

# in awesome_project/settings INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

...,

'hello',

]

Step 5: Start the server

Believe it or not, we’re now ready to start the server! Run the following command and the server should be running at the default port 6000 on your localhost (http://127.0.0.1).

# in awesome_project python manage.py runserver

You should see this message:

Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Congratulations! You have just started your first Django server!
Ruby 裡的迴圈跟迭代
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Basics of Node.js server creation
Tags: Nodejs, Node Js Development, Backend, Node Js Tutorial, Servers

After every change we need to restart the node server by node app.js. To avoid this you can install nodemon. Nodemon listens to the change done in the file and auto restarts the server.

Install nodemon globally by the following command

npm i -g nodemon

The server restarts after changes done to app.js file

3) Send requests and responses

We had created a server and the server is listening in port 3000. We’ll start sending request and get the request.

Inside the create server we have two params. First is the the request we had sent and the second is the response to be sent. Request.url gives the path that you had accessed from the server and request.method gives the type of method (GET, POST, PUT, DELETE)the API call was made. Response.write writes the response. We can use the Response.write in more than one place but after writing all responses we need to end (response.end()) the response otherwise the response won’t end and it can’t reach the user.

Open the URL.

Here you can see the the url is testing and its method is GET.

All calls made from browser window is of GET method. You can install the Talend API Tester — Free Edition extension on chrome or use Postman application for testing other methods.

By using the same url http://localhost:3000/testing the chrome extension gives the response as unknown because in response the content-type header is not sent but not in postman or browser. Because the browser will do MIME sniffing in some cases and will not necessarily follow the value of this header.(Reference from Link)

So we need to set the content type before we send the response.

After setting the content-type the result is displayed. The content-type should be set before writing the first response.write().

4) Setting routes

we have the bare minimum of a server. So we need to get different responses for different methods and url. The below code has a switch statement based on API call method.

This is a simple app with few routes.

What if we have multiple routes and sub routes. The app.js file will become large and complicated. That’s where the frameworks like ExpressJs comes to the rescue where we can have different files for different routes and sub routes and no need of mandatory setting of content-type or a messy app.js file. It is better to use middlewares and routes in app.js file.

PART 2 of this basics will cover ExpressJs (node framework )and middlewares like cors , formidable.

Stay tuned 😄 ✅
[Warehouse] 무료 API 모음
By: Dongmin Jang
Tags: HTML, API, Backend, JavaScript, Frontend

7 Free APIs That Nobody Is Talking About

Create unique and interesting apps using these APIs
디프만 8기 파이널 발표
By: Depromeet 디프만
Tags: Side Project, 디프만 8기, Backend, Ui Ux Design, Front End Development

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Ruby 裡的邏輯判斷與流程控制
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Advanced health check for Openresty (Nginx) backend
By: Lev Petrushchak
Tags: Lua, Nginx, Backend, Health Check, Openresty

At Quiq we are using Openresty as a replacement for the Nginx web server. This is an open-source Web Platform which extends Nginx with Lua scripting language.

I have faced an interesting case. Let’s say there are two upstream (backend) servers. One is main and used to serve traffic and another one is used by a separate “server” block for other purposes. Both backends are listening on different ports on localhost together with Openresty server. In order to send traffic to the main upstream, I need to know the health status of both upstreams. In case when either first or second is down, I need Openresty to return 503.

There is an advanced library for doing health checks https://github.com/openresty/lua-resty-upstream-healthcheck and while I figured out how to use this advanced library, I came to a more simple and elegant solution — use direct LUA in access_by_lua_block

So here I used core resty.http library and simple GET method to get the status of the server. The main backend must return HTTP 200 and “other” backend HTTP 204. As simple as that.

The final nginx.conf would look like this:

Worth to mention, Nginx itself has two built-in types of health checks for upstreams. Active and passive https://docs.nginx.com/nginx/admin-guide/load-balancer/http-health-check/ Passive health check is not quite what I needed and active health check is available only in Nginx Plus version
Test-Driven Development 測試驅動開發 (TDD)
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Measuring Performance of Different JavaScript Loop Types
By: Chameera Dulanga
Tags: Web Development, Backend, JavaScript, Frontend, Front End Development

Analyzing Will Give More Insights on Results

After going through the above results, you may question the differences between outputs in 2 browsers. The answer to that question is pretty straightforward, JavaScript engines of Chrome and Firefox are different from each other, and they use various optimization techniques.

Furthermore, let’s compare the results to see which loop has performed well.

Google Chrome — “for” is the Winner

Execution Times using Chrome Browser

In Google Chrome Browser, “for” Loop has shown the best performance with a minimum execution time while “for..in” showed the worst performance. The rest of the loops stays in the middle.

Firefox — “for”, “forEach”, “map” are joint Winners

Execution Times using Firefox Browser

When it comes to Firefox, “for”, “forEach” and “map” Loops showed the best performances (the variation is minimal). “While” and “DoWhile” performed the worst. The rest of the loops stays in the middle.

Execution Times Chrome vs Firefox

When we compare the results across browsers, except “While” and “DoWhile” the variation is minimal. You can also see that the “for” or “forEach” are the best options for both browsers.

These results are equally applicable to NodeJS since it uses the V8 JavaScript engine under the hood, developed for Chrome.

Summary

If you are given the option to select a single Loop, use “for”, which has the least execution time.

And I would encourage you to minimize the use of “While”, “DoWhile” which might cause inconsistencies in your execution time across Chrome and Firefox.

And it’s also essential to decide your strategy based on balancing performance and maintainability. Therefore, if you prefer a more functional coding style, choosing “forEach” is a safer bet.

Besides, if your Arrays are smaller, these differences won’t make much of a difference.

Thank you for Reading!!!
How to not lose any data in Kafka
By: Arash Rahimi
Tags: Message Queue, Kafka, Backend, Message Broker, Golang

In our company, we started a vital microservice with Golang. this service read messages from Kafka and after some processes save the result in the database

These messages are very important because they are such config messages and end-user will see the bad result if the messages did not proceed successfully

So we developed the microservice successfully and test it with unit tests all thing is done well

But after some days we received some reports demonstrate that some data not set successfully in the database and end-users nagging that something bad happened in our application

so we reviewed our code again and again and also unit tests but can not find anything or any situation that made the system lose data. but after days we have found the problem. but what was it?

When your program read messages from Kafka by default Kafka remove the message from his history as he thinks you proceed message successfully and Kafka named this operation COMMIT and in the default behavior all messages were read by user commit after 5 seconds. So our problem actually was that, the Kafka AUTO-COMMIT. we read messages from Kafka and sometimes because the database unreachable at the moment or when release a new version of our microservice the data cannot proceed successfully but because the message was read from Kafka and auto-commit was enabled the data disappear and bugs come up.

So that sound is weird, what should we do? it is so bad that we lose our data. don't be worried Kafka has an option that completely made our work easy.

For solving this issue when we want to connect Kafka as a consumer we should tell Kafka you should not commit our message, our microservice will

Talk is cheap, show me the code

disabling auto-commit is so easy, just pass an argument to Kafka as a consumer, for example, see our code written in Golang

consumer, err := kafka.NewConsumer(&kafka.ConfigMap{

"bootstrap.servers": option.Servers,

"group.id": groupId,

"enable.auto.commit": false,

})

so easy! but just one other easy step remains and that is, commit messages after procced the message, and it's simple too

just call the commit function in Kafka right after doing your work when you are sure you saved the data successfully or sending the message to the client is done .that send and Acknowledge to the Kafka server and Kafka removes this message for your topic.

in the example below that written in Golang, we sent a list of offsets that retrieved from messages read from Kafka, every message has a unique offset number that we can use in a commit

consumer.CommitOffsets([]kafka.TopicPartition{kafka.TopicPartition{

Topic: &topic,

Offset: kafka.Offset(offset),

}})

Finish. we are done our work successfully and now we are sure all data saved in the database

Note: if your data failed to proceed and you cannot commit your message, Kafka would recognize oh there is a problem and retry the message after a while

That is, hope you enjoy it.
Ruby 裡的變數、常數、字串及數字
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
모두싸인 백엔드 아키텍처 해부하기
By: Soohyun Kim
Tags: Modusign, Domain Driven Development, Engineering, Backend, 모두싸인

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Adding A Pub/Sub layer To Your Express Backend
By: Raggi Hosni
Tags: Nodejs, Web Development, Programming, Backend, JavaScript

Adding a Pub/Sub layer to your express backend can add an event-driven capability that makes handing certain operations more intuitive as well as provide better code separation.

Sometimes we might want to perform some actions or call third party services as a result of an event occurring in our app. For example sending a welcome email, a welcome sms or analytics data when a new user is registered which is very common in most apps these days.

Lets take the aforementioned example where we send email, sms and analytic data when a user registers. Traditionally this can be done by using imperative function calls as shown in the example below.

You can already see how this code will look like as we keep adding more actions, each action will add another imperative function call to a dependent service and the function will keep growing in size. You can also see that besides being hard to maintain, this approach violates the Single Responsibility Principle as well as has the potential for repetition across different events not only user registration.

Pub/Sub Layer

Adding a Pub/Sub layer can solve this problem by emitting an event (user registered with this email) and letting separate listeners handle the work.

We will utilize Node.js’s Event Emitter to do that.

First we will create a shared Event Emitter as well as specify the set of events we need.

Note: Due to Node.jS Caching, this will always return the same instance of eventEmitter (Singleton)

Now we can modify our code to emit a “user registration event”

Now Separate Services can listen on events and do their Job, For example the EmailService

Now all that is left is to create an instance of your event listening services when bootstrapping your express app to initialize their listeners, something like calling this function when initializing your app

You can already see how adding more actions won’t add any extra lines of code in the user registration function which provides code separation and embraces the event driven nature of Node.js.
How to set up a Hapi.js project and create your first route?
By: Khouloud Khezami
Tags: Hapi, Hapijs, Typescript, Backend, Rest Api

Hapi.js logo

Hapi.js is basically an abstraction layer on top of Node.js which makes it easier to create restful APIs with it.

In this Tutorial we will create a simple REST API with Hapi.js. We will start by setting up a project and adding all the dependencies needed, then setup the databases and create some fake data, and finally create the CRUD routes.

Ready? Let’s jump right into it then.

First things first, open your cmd and locate yourself where you want to create your new project.

create a folder for your project with mkdir test-hapijs

Go inside your folder with cd test-hapijs

& now initialize your project with npm init -y

This will allow us to install the following packages we need for this tutorial.

npm i @hapi/hapi reflect-metadata sqlite3 typeorm

since we are using typescript, we should also add the types for the libraries we have just installed, therefore run this command as well:

npm i @types/hapi @types/node ts-node-dev typescript -D

The ts-node-dev dependency will allow us to run our code as well as recompiling and re-running our code every time we make a change in our typescript files.

All good? Let’s get started. Open your project with your fav editor. (I personally use VSC)

In order to be able to run our typescript files we should add the following line “ts-node-dev”: “ts-node-dev” to our package.json under scripts.

Once you are done, create index.ts in your root folder.

Now we should go to the index.ts file and write an init function to create a server and run the code. To do so, please follow the following steps:

Don’t forget to call the init function at the end.

To Run the project, open your terminal and paste:

npm run ts-node-dev index.ts

Result

Hallelujah, you are all set up!

Now, let’s define our first hello world route!

To create a route we should do as follow:

The route should always receive an object that contains the HTTP method and a path. The handler is the function that will be executed when the path is called.

If you open your Postman & try calling the route you will definitely have this result.

This is the first part of the Hapi.js series.

I hope that it was a clear and straight forward explanation, please let me know if you have any questions at info@techsoupe.com

instagram: https://www.instagram.com/techsoupe/
5 acrónimos que todo programador en Python debe conocer
By: Hever Rubio
Tags: Programación, Python3, Backend, Python Programming, Python

B I O D E G R A D A B L E / Full-Stack Developer / CEO at LoopGk / CEO at Simdi / Chief Solutions Architect at Syncronik
Backend Developer: Harus Mulai Dari Mana?
Tags: Web Development, Backend, Indonesia, App Development, Developer

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Rails 裡的 N + 1 Query
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Build Your Simple Microservice!
By: Taufan Fadhilah Iskandar
Tags: Nodejs, Microservice Architecture, Microservices, Backend, Laravel

Photo by Kaleidico on Unsplash

Have you ever feel your application is hard to maintain? or hard to scale up? if so i suggest you to know what microservice is.

Based on microservice.io, microservice is an architectural style that structures an application as a collection of services that are:

- Highly maintainable and testable

- Loosely coupled

- Independently deployable

- Organized around business capabilities

- Owned by a small team

I can say microservice is a way to split up our modules into services that can scale up based on their focus. In example User Modules, when we migrate into microservice we need to create a new database to store user data and also a dedicated project. So the benefit is we can focus for one service thats make easier to scale up and maintain.

As i mention above, benefit of microservice is we can focus for each service and make easier to scale up and maintain. Of course it has many benefits from server perspective, code perspective, security perspective etc. For the cons, what i feel is we need more resource such as more engineer and more server resource.

So, in this article i will share how i build a simple microservice using different tech stack (Lumen PHP and Express Nodejs). The case is about Property (User have house). We will set Nodejs as a Gateway and User Service, for Property Service we are using Lumen.

The Architecture

Next, i will split into some articles that are:

1. Introduction of Microservice

2. Build API with Lumen for Microservice

3. Build API with Nodejs fro Microservice

4. Build API Gateway with Nodejs for Microservice

5. Using JWT as Authentication in API Gateway

Thats all for the introduction, next we are going to build API with Lumen. Thank you!
Node JS File System (fs Promise)
By: Fabio Kounang
Tags: Node, Web Development, Programming, Backend, JavaScript

Interact with file system asynchronously (with promise ,not callback)

Prerequisites

Javascript

Asynchronous (promise, async await)

Nodejs basic

Express framework

So, i’ve been using node JS for a long time, and when i want to interact with files, i have to require nodejs fs package to access the file system. And when i want to make our system asynchronous, for me it’s either wrap my code in promise (manually) or just use the fs async with callback. But recently I discovered that if i want to use fs with promises, we could use nodejs fs promise package. Let’s dive in !

What we’ll learn :

Write File Read File Check File Exists Delete File Read Folder

So, let’s get started ! i will make it as simple as possible so you can understand easily.

Getting Ready

npm init / npm init -y

npm install express

create app.js file

create folder <test-folder>

const express = require('express');

const app = express();

const promiseFs = require('fs').promises; // WRITE FILE

app.post('/write-file', async (req, res, next) => {

try {

let dummyJson = {

name: 'Eren Yeager',

age: 26,

hobby: ['Kill Titans', 'Fighting']

} let stringData = JSON.stringify(dummyJson)

await promiseFs.writeFile('./test.json', stringData);

res.send({ status: 'success' });

} catch (error) {

console.log('ERROR WRITE FILE : ', error);

}

}) // READ FILE

app.get('/read-file', async (req, res, next) => {

try {

let result = await promiseFs.readFile('./test.json', 'utf-8');

res.send({

status: 'success',

data: JSON.parse(result)

});

} catch (error) {

console.log('ERROR READ FILE : ', error);

}

}) // Check FOLDER EXIST

app.get('/check-folder', async (req, res, next) => {

try {

let result = await promiseFs.access('./test-folder', 'utf-8');

res.send({ status: 'success' });

} catch (error) {

console.log('ERROR READ FILE : ', error);

}

}); // Check FILE EXIST

app.get('/check-file', async (req, res, next) => {

try {

let result = await promiseFs.access('./test.json', 'utf-8');

res.send({ status: 'success' });

} catch (error) {

console.log('ERROR READ FILE : ', error);

}

}) // note that access method return undefined if folder exist, and throw error if no folder found res.send({ status: 'success' });

} catch (error) {

console.log('ERROR READ FILE : ', error);

}

}) // DELETE FILE

app.delete('/delete-file', async (req, res, next) => {

try {

let result = await promiseFs.unlink('./test.json', 'utf-8');

res.send({ status: 'success' });

} catch (error) {

console.log('ERROR READ FILE : ', error);

}

}) app.listen(3000, () => {

console.log('Listening to port 3000');

});

My test result

Write File

Read File

Check Folder

Check File

Delete File

That’s it guys, i hope it helps ! #sayyestocode
Rails 裡的 Partial Render ( 局部渲染 )
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Laravel — The Basics — Middleware (官方文件原子化翻譯)
By: Ray Lee
Tags: Laravel, Middleware, Documentation, Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Multiple Auth Scheme with AdonisJS
Tags: Nodejs, Web Development, Backend, Multiple Authentication, Adonisjs

so, hey guys….

I hope everyone is safe and doing great.

During the lockdown days I started learning backend development with NodeJs and took AdonisJs framework as Base. And trust me, it's really easy to build a production ready backend with the framework. Everything is ready out-of-the-box and needs very minimal configuration.

As I’m mainly a Mobile App Developer, I needed only apis to integrate into my apps, so I never tried AdonisJS Full-Stack variant before November . And the story begins here-

As I started learning web app development with the framework I always needed some api endpoints as well as some views to render for web. Then learned bootstrap and developed a simple admin portal. But there’s always a problem. For apis I needed JWT Auth and for web it needs Session Auth. And to overcome this situation, I setup two different Adonis app, one for apis only and other one for web with a common database. And till December I never had any idea the it also has different routing options for web and apis, also the auth scheme is changeable on-the-fly. Interesting ! right ?!

Let’s checkout how it can be done-

Let’s start by creating different routes for api and web-

create routes folder inside project’s root folder/start and three new files inside that routes folder (check below image)

Now write these two lines in index.js file

//start/routes/index.js require(‘./api’) require(‘./web’)

And now write web routes in web.js and api routes in api.js

Well, it’s time for changing auth.

Set default auth to “session” in “config/auth.js” file and rest is same for web routes and every auth related codes will remain same for web routes. Checkout documentation.

It’s time for api routes. As our default auth scheme is session we need to change auth scheme to JWT on-the-fly for api routes. Well nothing much to do; just add “ await auth.authenticator(‘jwt’).attempt(‘email’, ‘password’) or await auth.authenticator(‘jwt’).generate(user) ” instead of “ await auth.attempt(‘email’, ‘password’) or await auth.generate(user) ” and “auth.getUser()” remains same. Isn’t it easy ??

All of these things already mentioned in AdonisJS documentation.

Thanks for reading.
Rails 裡的 404
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Django ORM 模型層 ManyToMany(多對多)
By: 承諺 Harry Tsai
Tags: Postgresql, Backend, Orm, Django

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
▷ Librerías de Desarrolladores: La Biblioteca Única para los Profesionales de la Programación
By: Pablo Álvarez Corredera
Tags: Web Development, Programming, Backend Development, Backend, Front End Development

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Ruby 的區塊及方法
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
我喜歡使用 Laravel 開發的感覺, 除了開發快速, 程式碼簡潔且優雅之外, Laravel 框架本身也是一個很好的學習參照物 Laravel 的功能很多, 在進入 Laravel 底層的世界之前, 我希望可以初步的了解全部的功能, 我相信這會讓我在遇到問題時, 可以不必重新造輪子, 選擇 Laravel 已提供的最佳解法。 所以我詳讀 Laravel Documentation…
By: Ray Lee
Tags: Dev, PHP, Backend, Documentation, Laravel

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
淺談 Rails 的 MVC 架構
By: Henry Huang
Tags: Backend

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
a guide to creating a simple app
By: Godiya Joseph Zambwa
Tags: Web Development, Backend, Node Js Tutorial, NPM, App Development

Creating an app is not as hard as people think. Once you know the concept and basic steps, you’ll find out it is a simple task. I’m here to guide you on how to create a basic app. I’ll use Visual Studio Code as my editor. Also I will attach links for your personal consumption.

Terminologies:

NPM- Node Package Manager

NPX- Node Package Execute

Let’s begin!

STEP 1 (Create a new folder (I named mine myapp) and open the folder in your editor).

STEP 2 (In myapp create a new folder and name it controller (in the controller folder create two js files: users.js, tasks.js). In the routes folder create two js files (users.js and tasks.js).

STEP 3 (let’s create a skeletal application by generating express dependencies) https://docs.npmjs.com/about-npm

>npx express-generator

STEP 4

>npm install

STEP 5 https://sequelize.org/master/index.html

>npm i sequelize

STEP 6

>npm i mysql2

STEP 7 https://levelup.gitconnected.com/getting-started-with-sequelize-cli-c33c797f05c6

>npm install --save-dev sequelize-cli

STEP 8

>npx sequelize-cli init

STEP 9

>npx sequelize-cli db:create

STEP 10

>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string

STEP 11

>npx sequelize-cli db:migrate

STEP 12

>npx sequelize-cli seed:generate --name user

STEP 13 (edit user.js file under seeders folder, add createdAt and updatedAt)

STEP 15

>npx sequelize-cli db:seed:all

STEP 16 https://levelup.gitconnected.com/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233

>npx sequelize-cli model:generate — name Task — attributes title:string,userId:integer

STEP 17 (find tasks.js in the /models subdirectory within myapp and associate).

STEP 18 (find users.js in the /models subdirectory within myapp and associate)

STEP 19 (Edit object userId in task.js file in the migrations folder)

STEP 20

>npx sequelize-cli db:migrate

STEP 21

>npx sequelize-cli seed:generate — name task

STEP 22 (In the seeders folder edit and give Godiya a task ‘Design an app’).

STEP 23

>npx sequelize-cli db:seed:all

CONNECT THE ROUTES AND CONTROLLERS FOLDERS WITH app.js

STEP 24 (Work on users.js file in the controller folder)

STEP 25 (Work on users.js file in the routes folder)

STEP 26 (Work on tasks.js file in the controller folder)

STEP 27 (Work on tasks.js file in the routes folder)

STEP 28 (Try out the get, post, put and delete method using postman while confirming the outcome from phpmyadmin)
gRPC with Java
By: Diego Pacheco
Tags: Microservice, Java15, Java, Backend, Grpc

gRPC is a high-performance universal RPC framework. gRPC has support for interoperability between several languages such as Java, C++, C#, Go, Dart, Kotlin, NodeJS, Objective-C, PHP, Python, Ruby, Rust, and many more. gRPC has a schema for service definition and it can generate code based on that schema. gRPC also supports bi-directional streaming and authentication with HTTP/2 protocol. gRPC is battle-tested by Square, CoreOS, Cisco, CockroachLabs, Netflix, and many other companies. gRPC is also part of the CNCF project. Today I want to share a video made with gRPC and Java. So Let’s get started.

The Video

The Code

Cheers,

Diego Pacheco
Self, Static, $this 在 PHP 中的差異
By: Ray Lee
Tags: Backend, PHP, Oop

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore