Adam Rose

Adam Rose

1568951134

How to build a blogging engine using Node.js and TypeScript

As dynamically typed languages became prominent during the last decade, typeless (or should I say lawless?) programming became the norm for the backend as well as the frontend.

Many people believe the simplicity of “just writing” code is efficient for providing a proof of concept or prototyping applications.

However, as those applications grow, the typeless code used to build them often becomes incredibly convoluted and more difficult (some would say impossible) to manage.

In the worst cases, developers end up resorting to testing and prayer in the hopes that simple operations like renaming a function won’t break the whole complex system. However, developers can build their code from day one to make their codebase readable at scale.

TypeScript to the rescue

The key to making a large (or even small!) codebase readable is to keep track of all the data types flowing through the app.

To help developers with this, TypeScript provided a typed superset of plain old JavaScript. This means that a regular JavaScript developer’s existing knowledge applies to TypeScript.

There are other efficient ways developers can use their knowledge and code in new ways. Developers who use NodeJS can now recycle their frontend code for the backend, and vice versa.

Additionally, the introduction of static typing to JavaScript allows developers to reuse some of that old Java/C# knowledge to help maintain their NodeJS codebases.

Today’s Project: A Simple Blogging Engine

In this tutorial, we need a new backend for a blogging engine. This app will contain a list of blog posts, each with a title, content, and author.

The authors will be able to register and log in using the session-in-cookies approach. Okta will manage the users, and all blog posts will be saved in memory.

Documentation for the backend will be exposed as a Swagger specification generated from TypeScript typings for classes and methods.

Dependencies for the NodeJS Typescript Sample App

  • NestJS to bootstrap the server
  • Swagger to define the server docs
  • Okta for user management and authentication
  • NodeJS
  • validate-class npm library for input validation
  • nodemon to auto-restart the server on every change

Initialize

Create an empty directory bloggeur, cd into it, and type npm init there. After pressing the ENTER key a few times, a NodeJS project will initiate.

TypeScript config JSON

As TypeScript is very configurable, most TypeScript projects contain a configuration to select the language features it should use.

Create a tsconfig.json in the root of your project:

{
 "compilerOptions": {
   "target": "es2015",
   "lib": ["es2015"],
   "types": ["reflect-metadata", "node"],
   "module": "commonjs",
   "moduleResolution": "node",
   "experimentalDecorators":true,
   "emitDecoratorMetadata": true,
   "sourceMap": true,
   "declaration": false,
   "allowSyntheticDefaultImports": true,
   "esModuleInterop": true
 },
 "exclude": [
   "node_modules"
 ]
}

Add all the dependencies

npm install @nestjs/common@6.5.2 @nestjs/core@6.5.2 @nestjs/platform-express@6.5.2 @nestjs/swagger@3.1.0 @okta/okta-auth-js@2.6.0 @okta/okta-sdk-nodejs@2.0.0 @types/express@4.17.0 @types/node@12.6.2 class-transformer@0.2.3 class-validator@0.9.1 cookie-parser@1.4.4 dotenv@8.0.0 install@0.13.0 reflect-metadata@0.1.13 rxjs@6.5.2 swagger-ui-express@4.0.7 ts-node@8.3.0 typescript@3.5.3 glob@7.1.4 @types/glob@7.1.1

Most of these dependencies should be straightforward, but a few of them require a bit of explaining:

  • The authentication and authorization middlewares require the @okta packages
  • The @nestjs packages are a part of NestJS platform, a high-level wrapper around Express.js that powers the TypeScript metadata feature for API documentation
  • The reflect-metadata package exposes metadata features
  • class-transformer and class-validator validate client input before passing it to the controllers

Create the server startup

Create a point of entry (server.js) to set up the TypeScript context and run the project using a regular node command:

require('reflect-metadata'); // used to extract static data types at runtime, needed for automatic API docs generation
require('ts-node/register'); // used to transpile typescript code dynamically at runtime
require('dotenv/config'); // if it exists, loads .env file into process.env
require('./src/server.ts'); // entry into the TypeScript realm

Also, create a src directory, for the source code.

Create a NestJS module

Both Node.js and .NET heavily inspired NestJS. So it’s not surprising that every NestJS app is just a bunch of modules.

Create an (almost) empty NestJS module src/application.module.ts. It only contains a cookie-parser middleware, and will contain all of the application’s (currently non-existent) controllers:

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import glob from 'glob';

const controllers =
 glob.sync(‘.module/-controller.ts’, { cwd: __dirname, absolute: true }) // go through all the modules containing controllers
   .map(require) // require every one of them
   .map(imported => imported.default);
   // and return each one’s default export (which is expected to be a NestJS controller class)

@Module({
 controllers
})
export class ApplicationModule implements NestModule {
 configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
   consumer.apply(cookieParser()).forRoutes(‘/’);
 }
}

Bootstrap the NestJS server

Create src/server.ts to spin up the server:

import { NestFactory } from ‘@nestjs/core’;
import { ValidationPipe } from ‘@nestjs/common’;
import { SwaggerModule, DocumentBuilder } from ‘@nestjs/swagger’;
import { ApplicationModule } from ‘./application.module’;

async function bootstrap() {
 const app = await NestFactory.create(ApplicationModule); // Application module created in the step before
 app.useGlobalPipes(new ValidationPipe()); // Makes use of class-validate to sanitize data entering the API

 // Creates Swagger documentation and OpenAPI console on the root path (http://localhost:3000)
 const swaggerOptions = new DocumentBuilder().build();
 const document = SwaggerModule.createDocument(app, swaggerOptions);
 SwaggerModule.setup(‘/’, app, document);

 await app.listen(3000);
}

bootstrap().catch(console.error);

Test Run your Application

By running npm start or node server.js, your server should be started on port 3000.

But be sure to run it using nodemon to allow for automatic restarts:

npx nodemon server.js --ext ts

After running the server, direct your browser to http://localhost:3000. An API console should open with the message “No operations defined in spec”.

Now let’s create a few operations!

Create the BlogPost module

Create a directory src/blog-post.module. In it, create src/blog-post.module/blog-post-controller.ts to contain all the posts:

import { Controller, Get } from ‘@nestjs/common’;
import { ApiModelProperty, ApiResponse } from ‘@nestjs/swagger’;

export class BlogPost {
 @ApiModelProperty() // used to generate Swagger documentation that BlogPost model contains id of type number
 id: number;

 @ApiModelProperty()
 authorId: string;

 @ApiModelProperty()
 title: string;

 @ApiModelProperty()
 content: string;
}

export const blogPosts = [{
 id: 1,
 authorId: ‘xxx’,
 title: ‘Build a NodeJS App with Typescript’,
 content: ‘Whats wrong with Javascript?’
}, {
 id: 2,
 authorId: ‘yyy’,
 title: ‘Don’t build a NodeJS App with Typescript’,
 content: ‘Whats wrong with Typescript?’
}];

@Controller(‘blog-posts’)
export default class BlogPostController {
 @Get() // registers a blog-posts GET method on the API
 @ApiResponse({ type: BlogPost, status: 200, isArray: true }) // for Swagger documentation: API returns an array of BlogPost models
 findAll(): Array<BlogPost> {
   return blogPosts;
 }
}

Refresh browser page http://localhost:3000, and execute GET blog-posts in the API console.

Create the Authentication module

Create a directory for authentication module: src/auth.module.

To help offload the burden of authentication, you will use Okta for authentication, authorization, and user account management.

Create a forever-free Okta account and application

Click here to create an account.

Once you’re logged into your Okta dashboard, click Applications in the menu and click Add Application. From the wizard, choose Service and click Next.

On the Application Settings screen, name the application (I’ve named mine “the-blog-backend”).

After an application has been successfully created, copy the client ID and client secret into the .env file in the root of the project.

The dotenv (.env) file stores your development environment variables. They switch your application’s code from development to production or reference accounts on 3rd-party providers.

This file is consumed by the require(‘dotenv/config’) statement in your server.js file. It copies the values from .env file into the process.env global variable. Create an empty .env file in the root directory of the project.

The application needs an API token to communicate with Okta. In the Okta dashboard, click on API, then Tokens, and on the new page click Create Token. Copy its value to the .env file as well.

You’ll also put your Okta account’s domain in the .env file. It’s the hostname of the Okta dashboard you’re currently using, but without the -admin part. It should look something like dev-xxxxxx.okta.com.

After writing all those values, your .env file should look something like this:

OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}
OKTA_APP_TOKEN={yourAppToken}
OKTA_DOMAIN=https://{yourOktaDomain}

All these values are needed for the next section.

Integrate Authentication with Okta APIs

The Okta APIs you need for this project are the authentication API and the user management API.

Both are nicely exposed through npm packages @okta/okta-auth-js and @okta/okta-sdk-nodejs.

Create src/auth-module/okta-client.ts file to integrate with those services:

import { Client as OktaClient } from ‘@okta/okta-sdk-nodejs’;
import OktaAuth from ‘@okta/okta-auth-js’;

const { OKTA_DOMAIN, OKTA_APP_TOKEN } = process.env; // provided by .env file

const oktaClient = new OktaClient({
 orgUrl: OKTA_DOMAIN,
 token: OKTA_APP_TOKEN,
});

const oktaAuthClient = new OktaAuth({
 issuer: ${OKTA_DOMAIN}/oauth2/default,
});

export interface IRegisterData {
 firstName: string;
 lastName: string;
 email: string;
 password: string;
}

export interface IRegistrationResponse {
 id: string;
}

export async function register(registerData: IRegisterData): Promise<IRegistrationResponse> {
 const { email, firstName, lastName, password } = registerData;
 const createdUser = await oktaClient.createUser({
   profile: { email, login: email, firstName, lastName },
   credentials: { password : { value: password } }
 });

 return createdUser;
}

export interface ILoginData {
 email: string;
 password: string;
}

export interface ISession {
 sessionId: string;
 userId: string;
 userEmail: string;
}

export async function sessionLogin(loginData: ILoginData): Promise<ISession> {
 const { email: username, password } = loginData;
 const { sessionToken } = await oktaAuthClient.signIn({ username, password });

 const session = await oktaClient.createSession({ sessionToken });
 const { login, id, userId } = session;

 return { sessionId: id, userEmail: login, userId };
}

export async function getSessionBySessionId(sessionId: string): Promise<ISession> {
 const session = await oktaClient.getSession(sessionId);
 const { login, id, userId } = session;

 return { sessionId: id, userEmail: login, userId };
}

export async function getUserById(id: string) {
 const { profile: { firstName, lastName, email } } = await oktaClient.getUser(id);
 return { id, firstName, lastName, email };
}

You have now exposed the functions to register a user with Okta, generate a session ID using email and password, and fetch a user by their ID.

That’s all you need for user management and authentication for this project.

Create a Login Endpoint

To allow for authentication, you need a login endpoint. Create a src/auth.module/auth-controller.ts file:

import { Body, Controller, Post, Req, UnauthorizedException } from ‘@nestjs/common’;
import { ApiModelProperty, ApiResponse } from ‘@nestjs/swagger’;
import { sessionLogin } from ‘./okta-client’;
import { Request } from ‘express’;

/*
DTO is short for Data Transfer Object
DTO is an object that carries data between processes
In the context of web apps, it’s used to document type of data to be transferred between backend and frontend
*/
export class LoginDto {
 @ApiModelProperty()
 email: string;

 @ApiModelProperty()
 password: string;
}

export class LoginResponseDto {
 @ApiModelProperty()
 sessionId: string;

 @ApiModelProperty()
 userEmail: string;

 @ApiModelProperty()
 userId: string
}

@Controller(‘login’)
export default class AuthController {
 @Post()
 @ApiResponse({ type: LoginResponseDto, status: 201 })
 async login(@Body() data: LoginDto, @Req() request: Request): Promise<LoginResponseDto> {
   const { email, password } = data;
   try {
     const session = await sessionLogin({ email, password });
     request.res.cookie(‘sessionId’, session.sessionId);
     return session;
   } catch (e) {
     console.log(‘login error’, e);
     throw new UnauthorizedException(‘Invalid email or password’);
   }
 }
}

You can now refresh the Swagger page at http://localhost:3000 to try out the new login endpoint.

We currently have no way to register a user through the server, so you can use Okta’s dashboard to create one and then execute a login endpoint with the corresponding email and password.

Create endpoints to create and fetch users

Having said that, let’s create endpoints for user creation and fetching.

Create src/user.module file and in it, create a src/user.module/user-controller.ts file:

import { Body, Controller, Get, NotFoundException, Param, Post, Req } from ‘@nestjs/common’;
import { ApiModelProperty, ApiResponse } from ‘@nestjs/swagger’;

import { getUserById, register, sessionLogin } from ‘…/auth.module/okta-client’;
import { IsEmail, IsNotEmpty } from ‘class-validator’;
import { Request } from ‘express’;

export class User {
 @ApiModelProperty()
 id: string;

 @ApiModelProperty()
 email: string;

 @ApiModelProperty()
 firstName: string;

 @ApiModelProperty()
 lastName: string;
}

export class UserRegisterDto {
 @ApiModelProperty()
 @IsEmail()
 email: string;

 @ApiModelProperty()
 @IsNotEmpty()
 password: string;

 @ApiModelProperty()
 @IsNotEmpty()
 firstName: string;

 @ApiModelProperty()
 @IsNotEmpty()
 lastName: string;
}

@Controller(‘users’)
export default class UserController {
 @ApiResponse({ type: User, status: 201 })
 @Post()
 async create(@Body() userData: UserRegisterDto, @Req() request: Request): Promise<User> {
   const { email, password, firstName, lastName } = userData;
   const { id } = await register({ email, password, firstName, lastName });
   const { sessionId } = await sessionLogin({ email, password });
   request.res.cookie(‘sessionId’, sessionId);

   return { id, email, firstName, lastName };
 }

 @ApiResponse({ type: User, status: 200 })
 @Get(‘:id’)
 async find(@Param(‘id’) id: string): Promise<User> {
   try {
     const user = await getUserById(id);
     return user;
   } catch (e) {
     console.error(‘could not find user’, id, e);
     throw new NotFoundException(‘No such user’);
   }
 }
}

Everything is pretty much the same here except for the @IsEmail() and @IsNotEmpty() validators.

Those prevent a request from being executed if data sent to the server does not contain a valid email and non-empty first and last name and password.

You can try out those validators by refreshing http://localhost:3000 page and executing register endpoint with some faulty data.

Secure the API

We need two more things for a secure API: authentication middleware to identify a logged-in user and an is-authenticated guard to protect non-public endpoints from anonymous access.

Create a src/auth.module/auth-middleware.ts file:

import { NestMiddleware } from ‘@nestjs/common’;
import { Request, Response } from ‘express’;
import { getSessionBySessionId } from ‘./okta-client’;

export class AuthMiddleware implements NestMiddleware {
 async use(req: Request, res: Response, next: Function) {
   const { sessionId } = req.cookies;
   if (!sessionId) {
     return next();
   }

   try {
     req[‘auth’] = await getSessionBySessionId(sessionId);
   } catch (e) {
     console.log(‘session fetching failed’, e);
   }
   next();
 }
}

This middleware extracts sessionId from cookies and attaches session info to the auth key of the request object.

To use the created middleware, apply it to the Application module. src/application.module.ts should look like this after the change:

import { MiddlewareConsumer, Module, NestModule } from ‘@nestjs/common’;
import cookieParser from ‘cookie-parser’;
import glob from ‘glob’;

import { AuthMiddleware } from ‘./auth.module/auth-middleware’;

const controllers =
 glob.sync(‘.module/-controller.ts’, { cwd: __dirname, absolute: true })
   .map(require)
   .map(imported => imported.default);

@Module({
 controllers
})
export class ApplicationModule implements NestModule {
 configure(consumer: MiddlewareConsumer): MiddlewareConsumer | void {
   consumer.apply(cookieParser(), AuthMiddleware).forRoutes(‘/’);
 }
}

Next is the authentication guard. Create a src/auth.module/is-authenticated-guard.ts file:

import { CanActivate, ExecutionContext } from ‘@nestjs/common’;

export class IsAuthenticatedGuard implements CanActivate {
 canActivate(context: ExecutionContext) {
   const request = context.switchToHttp().getRequest();
   const { auth } = request;
   return !!auth;
 }
}

Now we’re finally ready to create a blog post!

Create a blog post

To allow blog post creation, let’s expand our BlogPost controller to add a create() method. The method should be secured against unauthenticated usage and also modified to use userId extracted from the user’s session.

This is what the src/blog-post.module/blog-post-controller.ts file looks like after adding the create() method:

import { Body, Controller, Get, NotFoundException, Param, Post, Req, UseGuards } from ‘@nestjs/common’;
import { ApiModelProperty, ApiResponse } from ‘@nestjs/swagger’;
import { IsAuthenticatedGuard } from ‘…/auth.module/is-authenticated-guard’;
import { IsNotEmpty } from ‘class-validator’;
import { getUserById } from ‘…/auth.module/okta-client’;
import { User } from ‘…/user.module/user-controller’;

export class BlogPost {
 @ApiModelProperty()
 id: number;

 @ApiModelProperty()
 authorId: string;

 @ApiModelProperty()
 title: string;

 @ApiModelProperty()
 content: string;
}

export class BlogPostDto {
 @ApiModelProperty()
 @IsNotEmpty()
 title: string;

 @ApiModelProperty()
 @IsNotEmpty()
 content: string;
}

// you also don’t need those dummy blog posts because they can be created through API now
export const blogPosts = new Array<BlogPost>();

@Controller(‘blog-posts’)
export default class BlogPostController {
 @Get()
 @ApiResponse({ type: BlogPost, status: 200, isArray: true })
 findAll(): Array<BlogPost> {
   return blogPosts;
 }

 @Post()
 @ApiResponse({ type: BlogPost, status: 201 })
 @UseGuards(IsAuthenticatedGuard)
 create(@Body() blogPostDto: BlogPostDto, @Req() req): BlogPost {
   const { content, title } = blogPostDto;
   const id = blogPosts.length + 1;
   const { userId } = req[‘auth’];

   const newBlogPost: BlogPost = { id, title, content, authorId: userId };
   blogPosts.push(newBlogPost);

   return newBlogPost;
 }

 @Get(‘:id/author’)
 async findAuthor(@Param(‘id’) blogPostId: string): Promise<User> {
   const blogPost = blogPosts.filter(post => post.id.toString() === blogPostId)[0];
   if (!blogPost) {
     throw new NotFoundException(‘No such blog post’);
   }
   return await getUserById(blogPost.authorId);
 }
}

After refreshing that http://localhost:3000 page again, you should finally be able to create blog posts (but only after a successful login).

Good job!

Congratulations. You have finished a small blogging engine using NodeJS and TypeScript.

You leveraged TypeScript’s typing system to both implement and document a simple REST API.

Notice how API documentation and implementation are held together rather than being written apart? That helps keep the docs and implementation in sync as the API evolves.



#node-js #typescript #javascript #web-development #angular

What is GEEK

Buddha Community

How to build a blogging engine using Node.js and TypeScript

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

sophia tondon

sophia tondon

1625114985

Top 10 NodeJs app Development Companies- ValueCoders

Node.js is a prominent tech trend in the space of web and mobile application development. It has been proven very efficient and useful for a variety of application development. Thus, all business owners are eager to leverage this technology for creating their applications.

Are you striving to develop an application using Node.js? But can’t decide which company to hire for NodeJS app development? Well! Don’t stress over it, as the following list of NodeJS app development companies is going to help you find the best partner.

Let’s take a glance at top NodeJS application development companies to hire developers in 2021 for developing a mind-blowing application solution.

Before enlisting companies, I would like to say that every company has a foundation on which they thrive. Their end goals, qualities, and excellence define their competence. Thus, I prepared this list by considering a number of aspects. While making this list, I have considered the following aspects:

  • Review and rating
  • Enlisted by software peer & forums
  • Hourly price
  • Offered services
  • Year of experience (Average 8+ years)
  • Credibility & Excellence
  • Served clients and more

I believe this list will help you out in choosing the best NodeJS service provider company. So, now let’s explore the top NodeJS developer companies to choose from in 2021.

#1. JSGuru

JSGuru is a top-rated NodeJS app development company with an innovative team of dedicated NodeJS developers engaged in catering best-class UI/UX design, software products, and AWS professional services.

It is a team of one of the most talented developers to hire for all types of innovative solution development, including social media, dating, enterprise, and business-oriented solutions. The company has worked for years with a number of startups and launched a variety of products by collaborating with big-name corporations like T-systems.

If you want to hire NodeJS developers to secure an outstanding application, I would definitely suggest them. They serve in the area of eLearning, FinTech, eCommerce, Telecommunications, Mobile Device Management, and more.

  • Ratings: 4.9/5.0

  • Founded: 2006

  • Headquarters: Banja Luka, Bosnia, and Herzegovina

  • Price: Starting from $50/hour

Visit Website - https://www.valuecoders.com/blog/technology-and-apps/top-node-js-app-development-companies

#node js developer #hire node js developer #hiring node js developers #node js development company #node.js development company #node js development services