Skip to content

Commit 4a10bb5

Browse files
committed
end of ws
1 parent 7c6c5f6 commit 4a10bb5

File tree

13 files changed

+210
-135
lines changed

13 files changed

+210
-135
lines changed

.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
SECRET=123
Lines changed: 32 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,39 @@
1-
console.log("let's get started")
2-
3-
/**
4-
* Intro
5-
*/
6-
7-
// EcmaScript, JavaScript, Node
8-
9-
/**
10-
* Versions
11-
*/
12-
13-
// Node Versions
14-
// https://nodejs.dev/en/about/releases/
15-
161
/**
172
* Globals
183
*/
194

20-
// https://nodejs.org/docs/latest/api/globals.html
215
// console.log(process.versions)
226
// console.log('process.cwd():', process.cwd())
237
// console.log('__dirname:', __dirname)
248
// console.log('__filename:', __filename)
259

26-
/**
27-
* Modules
28-
*/
29-
30-
// CommonJS
31-
// ESModules
32-
33-
/**
34-
* Env
35-
*/
36-
37-
// require('dotenv').config()
38-
// console.log(process.env.SECRET) // from .env
39-
// console.log(process.env.NODE_ENV)
40-
4110
/**
4211
* Scope
4312
*/
4413

4514
// var x = [5, 6, 7]
4615
// function scope() {
47-
// for (var i = 0; i < x.length; i++) {
48-
// var item = x[i]
16+
// for (let i = 0; i < x.length; i++) {
17+
// const item = x[i]
4918
// console.log(item)
5019
// }
51-
52-
// console.log(i)
53-
// console.log(item)
5420
// }
5521
// scope()
5622

5723
/**
5824
* Object and Array Literals
5925
*/
6026

27+
// const person = {
28+
// name: 'brad',
29+
// age: 54,
30+
// occupation: 'pilot',
31+
// }
32+
33+
// const { name, ...x } = person
34+
35+
// console.log(x)
36+
6137
/**
6238
* Function Types
6339
*/
@@ -70,23 +46,30 @@ console.log("let's get started")
7046
* Map, Filter, Reduce, Find, Includes
7147
*/
7248

49+
// const myArray = [1, 2, 3]
50+
51+
// const total = myArray.map((i) => i + 17).reduce((soFar, nextItem) => soFar + nextItem, 0)
52+
53+
// console.log(total)
54+
7355
/**
7456
* File System
7557
*/
7658

77-
// const fs = require('fs')
78-
// const path = require('path')
79-
// const dataPath = path.join(__dirname, `data.csv`)
80-
// const data = fs.readFileSync(dataPath, 'utf8')
59+
const fs = require('fs')
60+
const path = require('path')
61+
const dataPath = path.join(__dirname, `data.csv`)
62+
const data = fs.readFileSync(dataPath, 'utf8')
8163

82-
// let json = data
83-
// .split('\n')
84-
// .map((item) => {
85-
// const [id, name] = item.split(',')
86-
// return `{ "id": ${id}, "name": "${name}" }`
87-
// })
88-
// .join(',\n')
64+
let json = data
65+
.split('\n')
66+
.filter(Boolean)
67+
.map((item) => {
68+
const [id, name] = item.split(',')
69+
return `{ "id": ${id}, "name": "${name.trim()}" }`
70+
})
71+
.join(',\n')
8972

90-
// json = `{ "users": [${json}] }`
73+
json = `{ "users": [${json}] }`
9174

92-
// console.log(JSON.parse(json))
75+
console.log(JSON.parse(json))

lessons/02-promises/lecture/index.ts

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
1-
import fs from 'fs'
2-
import path from 'path'
3-
// const fsPromises = require('fs').promises // the way the docs show
4-
// import { promises as fsPromises } from 'fs' // the esm version
5-
// import fetch from 'node-fetch'
1+
// function getVehicle(url: string) {
2+
// return fetch(url).then((response) => response.json())
3+
// }
64

7-
const dataPath = path.join(__dirname, `data.csv`)
5+
// function getPersonVehicles(id: number): Promise<string[]> {
6+
// return fetch(`https://swapi.dev/api/people/${id}`)
7+
// .then((response) => response.json() as Record<string, any>)
8+
// .then((data) => data.vehicles)
9+
// }
810

9-
// Let's make this asynchronous
10-
const data = fs.readFileSync(dataPath, 'utf8')
11-
console.log(data)
11+
// getPersonVehicles(1)
12+
// .then((vehicles) => {
13+
// const promises = vehicles.map((url) => getVehicle(url))
14+
// return Promise.all(promises)
15+
// })
16+
// .then((allVehicles) => {
17+
// console.log(allVehicles)
18+
// })
19+
20+
import { query } from './db'
21+
22+
query('SELECT * FROM user').then((results) => {
23+
console.log(results)
24+
})

lessons/03-request-response/lecture/index.ts

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import z from 'zod'
2-
// import { fakeFetch } from './utils'
2+
import { fakeFetch } from './utils'
33

44
/****************************************
55
Part 1: Request
66
*****************************************/
77

88
// function getPerson(id: number) {
9-
// fetch(`https://swapi.dev/api/people/${id}`).then(() => {
10-
// console.log('Promise is resolved')
9+
// const req = new Request(`https://swapi.dev/api/people/${id}`)
10+
11+
// fetch(req).then((res) => {
12+
// console.log(res)
1113
// })
1214
// }
1315

@@ -42,26 +44,25 @@ import z from 'zod'
4244
Part 4: Typesafe Network Response
4345
*****************************************/
4446

45-
// const personSchema = z.object({
46-
// name: z.string(),
47-
// height: z.string().transform((val) => Number(val)),
48-
// })
47+
const personSchema = z.object({
48+
name: z.string(),
49+
height: z.string().transform((val) => Number(val)),
50+
})
4951

50-
// type Person = z.infer<typeof personSchema>
51-
52-
type Person = {
53-
name: string
54-
height: number
55-
}
52+
type Person = z.infer<typeof personSchema>
5653

5754
function getPerson(id: number) {
5855
return fetch(`https://swapi.dev/api/people/${id}`)
5956
.then((res) => res.json())
6057
.then((data) => {
61-
return data as Person
58+
const parsedResponse = personSchema.safeParse(data)
59+
if (parsedResponse.success) {
60+
return parsedResponse.data
61+
} else {
62+
}
6263
})
6364
}
6465

65-
getPerson(1).then((person) => {
66-
console.log(person)
67-
})
66+
getPerson(1)
67+
.then((data) => {})
68+
.catch()
Lines changed: 78 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,70 @@
1-
// import { User, createAccount, addAccountUser } from './users'
1+
import { User, createAccount, addAccountUser, emailUser, logNewUserStats } from './users'
2+
3+
// const myFn = async function () {
4+
// // here
5+
// }
6+
// const x = myFn()
7+
// console.log(x)
8+
9+
// ---
10+
11+
// async function wait(ms) {
12+
// await new Promise((res) => setTimeout(res, ms))
13+
// }
14+
15+
// async function somePromise(x) {
16+
// await wait(1000)
17+
// if (x === 4) {
18+
// // return Promise.reject('4 is no good')
19+
// throw '4 is no good'
20+
// }
21+
// return x
22+
// }
23+
24+
// async function main() {
25+
// console.time()
26+
// const array = [
27+
// somePromise(1),
28+
// somePromise(2),
29+
// somePromise(3),
30+
// somePromise(4),
31+
// somePromise(5),
32+
// somePromise(6),
33+
// ]
34+
35+
// console.timeEnd()
36+
// console.log(array)
37+
// const final = await Promise.allSettled(array)
38+
// console.log(final)
39+
// }
40+
41+
// main()
242

343
/****************************************
444
Part 1
545
*****************************************/
646

7-
function getVehicle(url: string) {
8-
return fetch(url).then((response) => response.json())
9-
}
47+
// async function getVehicle(url: string) {
48+
// return await fetch(url).then((res) => res.json())
49+
// }
1050

11-
function getPersonVehicles(id: number): Promise<string[]> {
12-
return fetch(`https://swapi.dev/api/people/${id}`)
13-
.then((response) => response.json() as Record<string, any>)
14-
.then((data) => data.vehicles)
15-
}
51+
// async function getPersonVehicles(id: number): Promise<string[]> {
52+
// const data = (await fetch(`https://swapi.dev/api/people/${id}`).then((response) =>
53+
// response.json()
54+
// )) as Record<string, any>
55+
56+
// return data.vehicles // we're returning a promise that resolves vehicles
57+
// }
58+
59+
// async function main() {
60+
// const vehicles = await getPersonVehicles(1)
61+
// const allVehicles = await Promise.all(vehicles.map((url) => getVehicle(url)))
62+
// return allVehicles
63+
// }
1664

17-
getPersonVehicles(1)
18-
.then((vehicles) => {
19-
const p = vehicles.map((url) => getVehicle(url))
20-
return Promise.all(p)
21-
})
22-
.then((allVehicles) => {
23-
console.log(allVehicles)
24-
})
65+
// main().then((finalResults) => {
66+
// console.log(finalResults)
67+
// })
2568

2669
/****************************************
2770
Part 2
@@ -33,13 +76,25 @@ getPersonVehicles(1)
3376
// return addAccountUser(account.accountId, user)
3477
// })
3578
// .then((user) => {
36-
// // emailUser(user)
37-
// // logNewUserStats(account.accountId)
79+
// emailUser(user)
80+
// logNewUserStats(account.accountId)
3881
// })
3982
// }
4083

41-
// signup({ name: 'brad' }).then(() => {
42-
// console.log('✅ User Added')
43-
// })
84+
async function signup2(inputUser: User) {
85+
const account = await createAccount() // 1s
86+
const user = await addAccountUser(account.accountId, inputUser) // 1s
87+
88+
// console.time('internal')
89+
return Promise.all([emailUser(user), logNewUserStats(account.accountId)]) // 1s
90+
// console.timeEnd('internal') // return
91+
}
92+
93+
async function main() {
94+
console.time('external')
95+
await signup2({ name: 'brad' })
96+
console.log('success')
97+
console.timeEnd('external')
98+
}
4499

45-
// // Remember "top-level" await
100+
main()

lessons/04-async-await/lecture/users.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,24 @@ export type DBUser = User & {
1010
userId: number
1111
}
1212

13-
export function createAccount(): Promise<Account> {
14-
return Promise.resolve({ accountId: 1 })
13+
async function wait(ms) {
14+
await new Promise((res) => setTimeout(res, ms))
1515
}
1616

17-
export function addAccountUser(accountId: number, user: User): Promise<DBUser> {
18-
return Promise.resolve({ userId: 5, name: user.name })
17+
export async function createAccount(): Promise<Account> {
18+
await wait(1000)
19+
return { accountId: 1 }
1920
}
2021

21-
export function emailUser(user: DBUser) {
22-
return Promise.resolve()
22+
export async function addAccountUser(accountId: number, user: User): Promise<DBUser> {
23+
await wait(1000)
24+
return { userId: 5, name: user.name }
2325
}
2426

25-
export function logNewUserStats(accountId: number) {
26-
return Promise.resolve()
27+
export async function emailUser(user: DBUser) {
28+
await wait(1000)
29+
}
30+
31+
export async function logNewUserStats(accountId: number) {
32+
await wait(1000)
2733
}

lessons/04-async-await/practice/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ main()
1515

1616
// // Re-write main to use async/await
1717

18-
// function main() {
19-
// wait(1000).then(() => {
20-
// console.log('Wait for one second')
21-
// })
22-
// }
18+
function main() {
19+
wait(1000).then(() => {
20+
console.log('Wait for one second')
21+
})
22+
}
2323

2424
/****************************************
2525
Practice: 2

0 commit comments

Comments
 (0)