As an asynchronous event driven JavaScriptruntime, Node is designed to build scalablenetwork applications.
is the package manager for JavaScript and theworld's largest software registry.
npm init
npm install -–save-dev typescript
npm i –D typescript
npm install -–save react react-dom
npm i –S typescript react react-dom
Those commands:
Dev packages only available during develepoment
Regular dependencies also in dist package
npm install --global -–save typescript
Installed in node folder
Available as cmd app
In most cases not recommended
npm install package-a@3.0.0 --package-lock-only
When packege was installed one day in version 1 on other machine next day could be installed in version 2
Lock prevents it
Also garantues installation order. Npm packages are not necessary installed in same order and this caused problems sometimes.
npm install express@latest --save --force
You can you install or update for updating packages
Please not update is not updating dev dependencies unless you add –dev flag
"*"
"^1.4.3" -> match any major 4.x.x
"3.4.1"
"~4.2.1" -> match any minor 4.2.x
{
"name": "my-project",
"version": "1.0",
"dependencies": {
// install update
"already-installed-versionless-module": "*", // ignores "1.0" -> "1.1"
"already-installed-semver-module": "^1.4.3" // ignores "1.4.3" -> "1.5.2"
"already-installed-versioned-module": "3.4.1"// ignores ignores
"not-yet-installed-versionless-module": "*", // installs installs
"not-yet-installed-semver-module": "~4.2.1" // installs installs
"not-yet-installed-versioned-module": "2.7.8"// installs installs
}
}
Typescript is superset of Javascript. It compiles Javascript but also give you option to use strong typing, additional syntactic suggar and transpiles to supported JS.
vars are hoisted and therefore should be avoided
var is replaced by:
console.log(a); // what value is a here?
a = 5;
var a;
let and const both keep their scope since declaration
const a = 5;
let b = 6;
let text = `string text ${expression} string text`;
function(input: any) { // we expect some object with value prop
let num: number? = input && input.value;
}
function(input: number) {
return input * 5;
}
can be rewritten to
(input: number): number => ({ input * 5});
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
// or later
const validator = await import { ZipCodeValidator } from "./ZipCodeValidator";
export function add(a: number, b: number): number {
return a + b;
}
export default function substract(a: number, b: number): number {
return a - b;
}
// or export default {add};
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
abstract class Greeter {
// same code as previous example
}
let greeter = new Greeter("world"); // can‘t do this!!!
class MyGreeter extends Greeter {
// some additional code
}
let greeter = new MyGreeter("world"); // possible now
interface IGreeter {
greeting: string;
greet();
}
class Greeter implements IGreeter { }
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }
let mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }
var o = {p: 42, q: true};
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
map()
every()
filter()
find()
findIndex()
reduce()
some()
There are synchronous and asynchronous operations.
Like: working with file system, network requests, ...
Before request is fulfilled (a lot of waiting involved), system can do other stuff. This is why you need async.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
myPromise
.then(handleResolvedC, handleRejectedC);
myPromise
.then(handleResolvedC)
.catch(handleRejectedAny);
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
try {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
} catch (e) {
// ...
}
}
= object-relational mapping
one of better Node ORM tools
It is written in Rust btw.
npm install prisma -D
npx prisma init
This creates .env and schema.prisma files.
DATABASE_URL = 'postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public'
Important: do NOT commit this to source control
model Post {
id Int @default(autoincrement()) @id
title String @db.VarChar(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
model Profile {
id Int @default(autoincrement()) @id
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model User {
id Int @default(autoincrement()) @id
email String @unique @db.VarChar(255)
name String? @db.VarChar(255)
posts Post[]
profile Profile?
}
npm install @prisma/client
npx prisma generate
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
}
main()
.catch(e => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
});
}
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}