반응형

Update

export const videoEditSave: ExpressRouter = async (req, res) => {
	const { id } = req.params;
	const { title, description, hashTags } = req.body;
	const videoId = id.replace("/edit", "");
	const video = await contentsModel.exists({ _id: videoId });

	if (!video) {
		return res.render("404", {
			pageTitle: `Not Found`,
		});
	}
	await contentsModel.findByIdAndUpdate(videoId, {
		title,
		description,
		hashTags: hashTags.split(",").map((word: string) => `#${word}`),
	});

	return res.redirect(`/video`);
};

 

- Mongoose - Pre

Pre는 새로운 객체를 저장할때 저장하기전 스키마의 행위를 지정해주는 미들 웨어이다.

예를 들면 해쉬태그를 작성한다면 input의 값을 쉼표로 나누어 작성했을 경우 하나의 객체로 만들어주며 하나의 객체 앞에 '#'을 붙여주는 행위를 한다 가정했을 때 아래와 같이 문장을 작성할 수 있다. 

Pre에는 두가지 인자를 받는데 첫번 째로는 방식이며 지정되어 있다. 두번째는 function을 입력해주면 된다.

contentsSchema.pre("save", async function () {
	this.hashTags =
		this.hashTags &&
		(this.hashTags[0] as string).split(",").map((word) => `#${word}`);
});

 

- Mongoose - Static

Static은 Pre와 비슷하지만 직접 function handler를 만들어준다고 생각하면 쉽다.

 

contentsSchema.static('hashFormat', function(hashTags){
	return hashTags.split(",").map((word:string) => `#${word}`)
})

 

//type script 경우에
import mongoose, { Model } from "mongoose";
import { IVideo } from "../types/type";
interface IHashformat extends Model<IVideo> {
	formatHash(hashTags: string): string[];
}
const contentsSchema = new mongoose.Schema<IVideo, IHashformat>({
	contentsForm: { type: String, required: true, trim: true },
	title: { type: String, required: true, trim: true, minLength: 3 },
	description: { type: String, required: true, trim: true, maxLength: 30 },
	createAt: { type: Date, required: true, default: Date.now() },
	hashTags: [{ type: String, trim: true }],
	meta: {
		views: { type: Number, required: true, default: 0 },
		rating: { type: Number, required: true, default: 0 },
	},
});


contentsSchema.static(
	"formatHash",
	function formatHash(hashTags: string): string[] {
		return hashTags.split(",").map((word: string) => `#${word}`);
	},
);
const contentsModel = mongoose.model<IVideo, IHashformat>(
	"Video",
	contentsSchema,
);
export default contentsModel;

 

Delete

export const deleteVideo: ExpressRouter = async (req, res) => {
	const { id } = req.params;
	const videoId = id.replace("/delete", "");
	const video = await contentsModel.exists({ _id: videoId });
	if (video) {
		await contentsModel.findByIdAndDelete(videoId);
		res.redirect("/video");
	} else {
		return res.render("404", {
			pageTitle: `Not Found`,
		});
	}
};

 

 

728x90
반응형

Generators

generator는 function 뒤에 *을 붙어주어야한다.

value와 done 값을 return 해 주며 값이 있을 때 value에 값이 나오고 done은 false다

library로도 많이 만들어져있고 fetch나 백엔드에서 조금은 사용이된다.

yield를 정하고 next로 호출하게 되면 하나씩 호출된다.

function* listHero() {
  yield "Thrall";
  yield "Thunderbluff";
  yield "Ogrima";
  yield "Boljin";
  yield "Silvanas";
  yield "Lor'themar Theron";
}

const callHero = listHero();

console.log(callHero.next());
console.log(callHero.next());
console.log(callHero.next());
console.log(callHero.next());
console.log(callHero.next());
console.log(callHero.next());

const herose = [
  "Thrall",
  "Thunderbluff",
  "Ogrima",
  "Boljin",
  "Silvanas",
  "Lor'themar Theron",
];

function* heroTeller() {
  for (const hero of herose) {
    yield hero;
  }
}

const heroLooper = heroTeller();

console.log(heroLooper.next());
console.log(heroLooper.next());
console.log(heroLooper.next());
console.log(heroLooper.next());
console.log(heroLooper.next());
console.log(heroLooper.next());

Proxy

proxy는 filter 처럼 생각 할 수 있다.

proxy는 두개의 인자를 받는다 object와 filter를 수행하는 handler를 받는다.

filterUser를 호춯하게되면 handler 부터 불려지고 다음 object를 반환하거나 반환을 하지 않는다.

handler에는 많은 trap들이 있다. trap들은 handler에 의해 만들어진다.

자세한 trap들은 mdn문서에 있으니 참고하면 됨.

const userObj = {
  name: "ChickenTau",
  age: 20,
  password: 123,
};

const userFilter = {
  get: (target, prop, receive) => {
    console.log(target);
    console.log(prop);
    console.log(receive);
    return target[prop];

    console.log("somebody getting some");
  },
  set: () => {
    console.log("somebody Wrote some");
  },
};
const filterUser = new Proxy(userObj, userFilter);

console.log(filterUser.name);
console.log(filterUser.age);
console.log(filterUser.password);
console.log((filterUser.level = 10));

 

Generator와 Proxy는 대부분 library를 제작할때 사용된다.

728x90
반응형

Database

데이터베이스에 데이터를 올리기 위해서는 일단 Get과 Post에 대해 알아야한다. 이를 위해서 html의 form을 이용해서 POST를 보내주어야한다.

이를 이해하기 위해 Fake data base를 만들어보자

// Data
const videos: IContentsModel[] = [
	{
		id: 1,
		title: "hoho",
		desc: "fhj",
		createAt: new Date().toLocaleDateString(),
	},
	{
		id: 2,
		title: "heeh",
		desc: "werte",
		createAt: new Date().toLocaleDateString(),
	},
	{
		id: 3,
		title: "hahah",
		desc: "ryftujkty",
		createAt: new Date().toLocaleDateString(),
	},
	{
		id: 4,
		title: "asdf",
		desc: "asfdasdf",
		createAt: new Date().toLocaleDateString(),
	},
];

그리고 front를 만들어주어 back으로 보낼 준비를 해주자. 여기서 중요한 것은 form의 메소드를 POST로 설정해주어야한다. 만약 url의 설정을 바꾸고 싶다면 action attribute를 주어 url도 설정할 수 있으나 같은 url주소로 POST를 할꺼니 action은 따로 지정하지 않았다.

extends ../layout/layout
block contents 
    div 
        form(method="POST") 
            legned(hidden) EDIT #{video.title}
            label(for="videoTitle") EDIT #{video.title}
            input#videoTitle(type="text", name="title" value=video.title) 
            input(type="submit" value="submit")

 

해당 화면을 볼수 있게 라우터와 controller middleware를만들어준다.

 movieRouter.get("/:id([0-9]/edit)", videoEdit);
export const videoEdit: ExpressRouter = (req, res) => {
	const { id } = req.params;
	const videoId = +id.replace("/edit", "") - 1;
	const video = videos[videoId];
	return res.render("./videoTemp/videoEdit", {
		pageTitle: `EDIT ${video.title.toUpperCase()}`,
		video,
	});
};

POST를 위한 Router를 만들어준다.

movieRouter.post("/:id([0-9]/edit)", videoEditSave);

 

 

movieRouter.get("/:id([0-9]/edit)", videoEdit);
movieRouter.post("/:id([0-9]/edit)", videoEditSave);

 

router 설정에 get 과 post를 한 줄로 정리할 수 있는데

movieRouter.route("/:id([0-9]/edit)").get(videoEdit).post(videoEditSave);

로 축약할 수 있다.

 

그리고 POST의 controller middleware 설정을 해주면 끝

export const videoEditSave: ExpressRouter = (req, res) => {
	const { id } = req.params;
	const { title } = req.body;
	const videoId = +id.replace("/edit", "");
	const video = videos[videoId - 1];
	video.title = title;
	return res.redirect(`/video/${videoId}`);
};

 

MongoDB

mongoDB는 다목적이고 document(문서) 기반으로 작동한다. 보통 database는 문서기반이 아니다 sql 기반이다. 엑셀시트 같은 개념이다. mongoDB에서 DB는 object로 움직인다. 행으로 저장이 되지않고 Array Object들로 구성이 된다. JSON처럼 저장된다는 느낌이라고 생각하면 된다.

Install

MongoDB Community Server를 다운 받아준다. 

Connecting

Mongoose

mongoose는 NodeJS와 MongoDB를 이어주는 매개체가 될것이다. mongo가 잘 설치 되었는지 확인하기 위해 터미널에 아래의 명령어를 입력해준다. not found 문구가 나오면 다시 설치해야한다.

mongod

그리고 아래 입력

mongosh
mongosh 명령어

help
show dbs
db.

 

VScode로 돌아와서 mongoose 설치

npm install mongoose --save

mongoDB와 연결해주기 위해 코드를 작성해야한다. src 폴더에 db.ts or js를 생성

import mongoose from "mongoose";
//mongosh에 나와있는 connecting to 참조
mongoose.connect("mongodb://로컬호스트:포트넘버/임의 저장소 이름을 지정",{});

백엔드 파일에가서 db.ts or js 파일 자체를 import를 해주어야한다. 경고나 주의가 터미널창에 나오면 ,{} 안에 터미널창에 나오는 데로 작성해주면 된다.

연결의 성공 여부나 에러를 console.log로 출력하기 위해 다음과 같이 문장을 추가한다.

mongoose.connection.once("connected", () => console.log("✅ DB is connected"));
mongoose.connection.on("error", (error) => console.log(error));
728x90
반응형

Classes

Classes는 object이다. 대부분 classes를 스스로 만들어 쓰지는 않을 것이다. 라이브러리나 리액트(Class문) 같은 것을 만들 때 사용한다. 코드를 구성하는데 도움을 준다. 많은 코드를 가지고 있고 구조화할때 사용하면 좋다. 

Constructor

class는 constructor(생성자)를 안에 가지고 있다. 또한 class 안에는 this라고 불리는게 있다. this는 기본적으로 class안에서 볼 수 있고 , 클래스 그자체를 가르킨다.
class 를 사용하기 위해서는 new를 사용해서 사용을 선언해줘야한다.  또한 class에는 함수도 만들 수 있다.  class는 object를 생성하는 공장이라고 볼 수 있다.

 

class HordUser {
  constructor(name, age, weapon, job) {
    this.basename = name;
    this.age = age;
    this.weapon = weapon;
    this.job = job;
  }
  
  sayHello() {
    console.log(`Rok tar Ogar ${this.basename}`);
  }

  changeWeapon(newWeapon, currentWeapon) {
    if (currentWeapon === this.weapon) {
      this.weapon = newWeapon;
      console.log(`changed new weapon ${newWeapon}`);
    } else {
      console.log("cant change weapon");
    }
  }
}


const thrall = new HordUser("thrall", 30, "axe", "great cheif");
console.log(thrall.basename);
thrall.sayHello();

const thunderbluff = new HordUser(
"thunderbluff",
40,
"greate axe",
"tauren cheif"
);

console.log(thunderbluff.basename);
thunderbluff.sayHello();
thunderbluff.changeWeapon("dagger", thunderbluff.weapon);
 
Constructor를 오브젝트로 만들어서 활용할수 있다. 이렇게 하는게 가독성이 더  좋을 수 있다.
class HordUser {
  constructor({name, age, weapon, job}) {
    this.basename = name;
    this.age = age;
    this.weapon = weapon;
    this.job = job;
  }
  sayHello() {
    console.log(`Rok tar Ogar ${this.basename}`);
  }
  changeWeapon(newWeapon, currentWeapon) {
    if (currentWeapon === this.weapon) {
      this.weapon = newWeapon;
      console.log(`changed new weapon ${newWeapon}`);
    } else {
      console.log("cant change weapon");
    }
  }
}

const thrall = new HordUser({
name: "thrall",
age: 30,
weapon: "axe",
job: "great cheif",
});

console.log(thrall.basename);
thrall.sayHello();


const thunderbluff = new HordUser({
name: "thunderbluff",
age: 40,
weapon: "greate axe",
job: "tauren cheif",
});

console.log(thunderbluff.basename);
thunderbluff.sayHello();
thunderbluff.changeWeapon("dagger", thunderbluff.weapon);

 

extending classes &  super

extending class에 새로운 constructor를 하기 위해서는 super라는 것이 필요하다. 그냥 contructor를 사용하게 되면 기존에 있던 것들은 없어져 버린다.
class AlianceUser extends HordUser {
  constructor({mana = 100, name, age, weapon, job, where}) {
    super({name, age, weapon, job});
    this.where = where;
    this.mana = mana;
  }
  
  aliaceSayHello() {
    console.log(`Greeting ${this.basename}`);
  }

  info() {
    console.log(this.basename, this.age, this.weapon, this.job, this.where);
  }

  checkMana() {
    this.mana = this.mana + 10;
    console.log(this.mana);
  }

  useMana() {
    this.mana = this.mana - 20;
    console.log(this.mana);
  }
}


const anduin = new AlianceUser({
name: "anduin",
age: 17,
weapon: "Sword",
job: "Healer",
where: "stormwind",
});

anduin.aliaceSayHello();

anduin.info();

console.log(anduin.mana);
console.log("/////");
anduin.useMana();
anduin.useMana();

console.log(anduin.mana);
anduin.checkMana();
anduin.checkMana();
anduin.checkMana();
anduin.checkMana();
console.log("/////");

console.log(anduin.mana);

 

만약 checkMana와 useMana를 HTML DOM과 연동해서 사용하려면 "checkMana(){}" 이 아닌 "checkMana=()=>{}"의 방법으로 해야한다.

 

728x90

'CODING PRACTICE > JavaScript & ES6' 카테고리의 다른 글

ES6__007(Generators / Proxy)  (0) 2024.01.01
ES6__006(Symbols, Set, WeakSet)  (0) 2023.12.28
ES6__004(Promises / async &. await)  (0) 2023.12.21
ES6__003(Spread / Rest / for of Loop)  (0) 2023.12.20
ES6__002(Array & Destructuring)  (0) 2023.12.01
반응형

Node.js란?

v8 자바스크립트 엔진으로 빌드 된 자바스크립트 런타임. 브라우저 밖에서 돌아가는 자바스크립트

프로젝트생성

1.먼저  해당 폴더를 git을 활성화 해준다.

git init

 

2. VScode에서 터미널에

npm init

 

작성후 package.json을 만들어주고 작성해준다.

index.js를 만들어주고 package.json의 script에 index.js를 실행하게 만들어주는 텍스트 작성 후 저장

"dev": "node src/server.js"

index.js에서 console.log로 아무 글이 나오게 만들고

npm run dev

 

를 실행하면 vscode 터미널에 내용이 나온다.

----

babel로 최신 javascript compile하는 방법

https://babeljs.io/

 

Babel · Babel

The compiler for next generation JavaScript

babeljs.io

node가 최신 javascript를 이해하기 위해 babel을 설치해주어한다.

해당 홈페이지의 setup에 들어가 Language APIs에 있는 node를 클릭하고 설치해주고 설명서대로 진행하면 된다. 또한 Nodemon을 사용하게 되는 경우에는 Utilities의 nodemon을 눌러 진행해준다.

 

** typescript로 진행하게 될 경우 (babel 설치 필요가 없음)

npm install --save-dev @types/node ts-node typescript

tsconfig.json을 만들기 위해 아래 입력

npx tsc --init

tsconfig.json이 만들어지고 혹시 include와 exclude를 찾을 수 없다고 하면 아래와 같이 입력

{
  "compilerOptions":{
    어쩌고 저쩌고
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

package.json에서 아래와 같이 변경

"dev": "ts-node src/server"

다시 아래의 명령어를 입력하여 잘 작동되는지 확인

npm run dev

** typescript를 설치 했다면 간혹 다른 도구를 설치하면 설치한 도구가 뭔지 몰라 빨간 줄이 그어질때가 있는데 당황하지 말고 마우스를 올리면 @types/도구이름 을 설치하라고 나오니 설치하면 잘 작동될것이다.

nodemon 설치

작업을 하면서 계속해서 'dev'명령어를 칠 수 없으니 nodemon을 사용해줘서 개발환경에서 백엔드가 지속적으로 동작할 수있게 만들어주어야 하는데 이때 도움을 줄수 있는 것이 nodemon이다.

npm i nodemon --save-dev

실행문을 바꿔준다.

"dev": "nodemon --exec ts-node src/server"

 

nodemon 파일 변경 감지 설정

//nodemon.json

{
  "ext": "ts,json,tsx"
}

ESLint / Prettier 설정

npm init @eslint/config
//프로젝트 루트 폴더 위치에서 터미널에
npm i -D prettier eslint-config-prettier

//명령어를 입력하여 prettier와 eslint-config-prettier 패키지를 설치합니다.
//프로젝트 루트 폴더 위치에 .prettierrc 파일 (prettier 설정 파일)을 생성합니다.
// 아래를 참고하여 prettier 옵션들을 .prettierrc 파일에 작성합니다. 추가적인 옵션들은 Prettier Options를 참고하시면 됩니다.

{
  // 쌍따옴표 대신 홑따옴표 사용
  "singleQuote": true,
  // 모든 구문 끝에 세미콜론 출력
  "semi": true,
  // 탭 대신 공백으로 들여쓰기
  "useTabs": false,
  // 들여쓰기 공백 수
  "tabWidth": 2,
  // 가능하면 후행 쉼표 사용
  "trailingComma": "all",
  // 줄 바꿈할 길이
  "printWidth": 80,
  // 객체 괄호에 공백 삽입
  "bracketSpacing": true,
  // 항상 화살표 함수의 매개 변수를 괄호로 감쌈
  "arrowParens": "always",
  // OS에 따른 코드라인 끝 처리 방식 사용
  "endOfLine": "auto"
}

.eslintrc에 가서

extends: ['기존 설정들', 'prettier']

또한 extent에서 eslint와 prettier를 설치해주고

vscode setting.json에 아래 추가

// 파일을 저장할 때마다 `eslint` 규칙에 따라 자동으로 코드를 수정
"editor.codeActionsOnSave": { "source.fixAll.eslint": true },
// `prettier`를 기본 포맷터로 지정
"editor.defaultFormatter": "esbenp.prettier-vscode",
// 파일을 저장할 때마다 포매팅 실행
"editor.formatOnSave": true,

 

Server란?

서버는 항상 켜져있고, 인터넷에 연결되어 있으며 request를 listening하고 있는 컴퓨터이다.

request란?

request는 우리가 서버에게 요청하는 것들이다. 브라우저로 웹사이트로 들어가는 행위가 request를 보내는것이다. 이 행위는 행위를 listening 하고 있는 서버에만 적용된다. 또한  get이외에 CRUD가 기반이 되는 post, delete, put 등등이 있다.

controllers

해당 url로 이동하려고 하면 그에 대한 동작을 실행하는게 controller이다. 여기서 request 와 response를 제공하게 되는데  request에는 누가 웹사이트를 request 했는지 cookies, 브라우저 정보 , IP 주소 같은 정보들이 있다. response에는 여러 메소드가 있다. cookie 설정부터 무엇을 보내고 렌더링하고 응답을 끝내는 등 많은 메소드가 있다.

 

middleware란? 

request와 response 중간에서 동작하는 함수 따위를 middleware라고 한다. 

middleware는 controller와 비슷하다. 보안이나 CRUD를 구현할때 같이 쓰인다.

NodeJS server 만들기  /  동적 및 정적 라우팅

import http, { IncomingMessage, ServerResponse } from "http";
import url from "url";

type HandleMap = {
	// eslint-disable-next-line no-unused-vars
	[path: string]: (req: IncomingMessage, res: ServerResponse) => void;
};
const server = http.createServer(
	(req: IncomingMessage, res: ServerResponse) => {
		const path = url.parse(req.url + "", true).pathname; // 패스명 할당
		res.setHeader("Content-Type", "text/html"); //응답 헤더 설정
		if (path && path in urlMap) {
			urlMap[path](req, res);
		} else {
			notFound(req, res);
		}
		// if (path === "/user") {
		// 	user(req, res);
		// } else if (path === "/feed") {
		// 	feed(req, res);
		// } else {
		// 	notFound(req, res);
		// }
	},
);

server.listen("5040", () => console.log("server is good"));
//동적
const user = (req: IncomingMessage, res: ServerResponse) => {
	const userInfo = url.parse(req.url + "", true).query;
	res.end(`[user] name : ${userInfo.name}, age : ${userInfo.age}`);
};
//정적
const feed = (req: IncomingMessage, res: ServerResponse) => {
	res.end(`
        <ul>
        <li>pictuer1</li>
        <li>pictuer2</li>
        <li>pictuer3</li>
        </ul>`);
};
const notFound = (req: IncomingMessage, res: ServerResponse) => {
	res.statusCode = 404;
	res.end("404 page not found");
};
const urlMap: HandleMap = {
	"/": (req: IncomingMessage, res: ServerResponse) => res.end("Home"),
	"/user": user,
	"/feed": feed,
};

express로 서버만들기

express를 사용하면 순수 nodejs로 서버를 만드는것보다 좀 더 쉽게 만들수있다.

import express, { Request, Response } from "express";

const PORT = 5040;
const app = express();

const middleWare: express.RequestHandler = (req, res, next) => {
	console.log("hohoho");
	next();
};
const user = (req: Request, res: Response) => {
	return res.send("user Page");
};
app.use(middleWare); //global 하게 미들웨어를 동작시킬 수 있다.

app.get("/", (req, res) => {
	return res.send("hi");
});
app.get("/music", (req, res) => {
	return res.send("music page");
});

app.get("/user", middleWare, user); // 해당 url에서만 미들웨어를 동작시킬 수 있다.

const handleListen = () =>
	console.log("✅ Server is Listenin on http://localhost:5040");
app.listen(PORT, handleListen);

 

 

 

app.get()으로 request를 요청 할 수 있다.

app.use()로 글로벌하게 MiddleWare를 동작시킬수 있다. 주의할점은 app.use 보다 위에 작성해야한다.

 

morgan - middle ware

node용 request logger middle ware이다.

npm i morgan
app.use(morgan("dev"));
// dev 말고도 다른것들도 있음

이렇게 하면 백엔드에서 morgan은 request method , path , status code 응답시간 정보를 가지고 있다.

728x90
반응형

Create Promise

Promise 생성

  • resolve는 값 => 자바스크립트로 return 되는 값
  • reject는 에러 => 에러가 나 거절되는 값
  • Promise의 핵심은 우리가 아직 모르는 값과 함께 작업할 수 있게 해준다.
const hoho = new Promise((resolve, reject) => {
resolve(`http://google.com`);
reject("wht t f?");
});

 

Using Promise

Promise 사용방법

  • Promise를 사용해주기 위해 then을 사용해준다.
hoho.then((value) => console.log(value)).catch((value) => console.error(value));

 Chaining Promise

결과 값이 여러개 나와야 하는 경우에 사용되어야한다.
Chainging 후에는 결과값에 대한 값을 return 해줘야한다.
hoho
.then((value) => {
  console.log(value);
  return value;
})
.then((secondVal) => {
  console.log(secondVal + " is good");
  return; // <= 3번째에서 오류가 던져진다.
  // return secondVal + " is good" //<= 3번째에서 오류없이 진행된다.
})
.then((thirdVal) => {
  if (thirdVal === undefined) {
    throw Error("there is no value");
  } else {
    console.log(thirdVal + " haha hoho");
  }
})
.catch((value) => console.error(value));

Promise all

주어진 모든 Promise를 실행 후 진행되는 하나의 Promise를 반환한다. 
const promiseNoOne = new Promise((resolve) => {
setTimeout(resolve, 5000, "first");
});

const promiseNoTwo = new Promise((resolve) => {
setTimeout(resolve, 8000, "second");
});

const promiseNoThird = new Promise((resolve) => {
setTimeout(resolve, 3000, "third");
});

const callAllThem = Promise.all([promiseNoOne, promiseNoTwo, promiseNoThird]);

callAllThem.then((val) => console.log(val));

 

Promise.race

어느 것이 먼저 되는지 상관 없을 때 race를 사용하면 된다. 제일 빨리 온 데이터 만 출력이된다.
const promiseNoOne = new Promise((resolve, reject) => {
setTimeout(resolve, 5000, "first");
});

const promiseNoTwo = new Promise((resolve) => {
setTimeout(resolve, 8000, "second");
});

const promiseNoThird = new Promise((resolve) => {
setTimeout(resolve, 3000, "third");
});

const callAllThem = Promise.race([promiseNoOne, promiseNoTwo, promiseNoThird]);

callAllThem.then((val) => console.log(val));

 

async/await

기본적으로 Promise를 사용하는 코드를 더 좋게 보이게 하는 문법이다.
** 기존 Promise
const getApiData = () => {
  fetch("API DATA URL")
    .then((response) => response.json())
    .then((json) => console.log(json))
    .catch((e) => console.error(e));
};

getApiData();
await는 항상 async가 필요하다.
const fetchApiData = async () => {
  const response = await fetch(`Api Data URL`);
  const json = await response.json();
  console.log(json);
};

fetchApiData();

async/await 의 catch

try catch finally 문

const fetchApiData = async () => {
  try {
    const response = await fetch(`Api Data URL`);
    const json = await response.json();
    console.log(json);
  } catch (e) {
    console.error(e);
  } finally {
    console.log("Done");
  }
};

parallel Async Await

여러개의 데이터를 fetching 하고 싶을 때
const fetchApiData = async () => {
  try {
    const [firstData, secondData] = await Promise.all([
      fetch(`Api Data URL No.1`),
      fetch(`Api Data URL No.2`),
    ]);

    const [firstJson, secondJson] = await Promise.all([
      firstData.json(),
      secondData.json(),
    ]);

    return [firstJson, secondJson];
  } catch (e) {
    console.error(e);
  } finally {
    console.log("Done");
  }
};
728x90

'CODING PRACTICE > JavaScript & ES6' 카테고리의 다른 글

ES6__006(Symbols, Set, WeakSet)  (0) 2023.12.28
ES6__005 (Classes)  (1) 2023.12.23
ES6__003(Spread / Rest / for of Loop)  (0) 2023.12.20
ES6__002(Array & Destructuring)  (0) 2023.12.01
ES6 __001 (Arrow Fuctions , String)  (1) 2023.11.21
반응형

Spread란 

기본적으로 변수를 가져와서 풀어 해치고 전개한다.

쉽게 말하자면 선물 포장지를 풀어해치는 행위이다.

const days = ["mon", "tue", "wed", "thu", "fri"];

console.log(...days);

 

const days = ["mon", "tue", "wed", "thu", "fri"];
const date = [1, 2, 3, 4, 5];

// 아래의 값은 서로 다르다. 

console.log([days, date]); // array 속에 array로 표현된다.
console.log([...days, ...date]); // array를 풀어 해쳐 하나의 array로 만들어준다.


//------//
const days = {day: ["mon", "tue", "wed", "thu", "fri"]};
const date = {number: [1, 2, 3, 4, 5]};

console.log({...days, ...date});

Rest란

Spread가 풀어해치는거면 Rest는 다시 포장하는 것이다.

const arg = (...data) => console.log(data);

arg(1, 2, 3, "hoho", "haha", false);


const arg = (a, b, c, ...data) => {
  console.log(a);
  console.log(b);
  console.log(c);
  console.log(data);
};

arg("hoho", 1, false, 2, 3, "haha");

Rest + Spread + Destructure

const user = {
  name: "hoho",
  age: 11,
  food: "apple",
};

const setUser = ({country = "jp", food: FOOD, ...rest}) => ({
  country,
  ...rest,
  FOOD,
  age: 22,
});

console.log(setUser(user));

 

For of Loop

For of Loop는 변수 값을 통해서 Loop를 조건문을 만들 수가 있다.

const kr = [
  "seoul",
  "gangneung",
  "busan",
  "jeju",
  "changwon",
  "junjoo",
  "gwangjoo",
];

for (const local of kr) {
  if (local === "changwon") {
    break;
  } else {
    console.log(local);
  }
}
728x90

'CODING PRACTICE > JavaScript & ES6' 카테고리의 다른 글

ES6__005 (Classes)  (1) 2023.12.23
ES6__004(Promises / async &. await)  (0) 2023.12.21
ES6__002(Array & Destructuring)  (0) 2023.12.01
ES6 __001 (Arrow Fuctions , String)  (1) 2023.11.21
Pagination 공식  (0) 2023.08.10
반응형

React Native와 FireBase연동하기 

https://rnfirebase.io/

1. 파이어베이스에 새 프로젝트 만들기

 

2. 파일 설치

npm install --save @react-native-firebase/app

React Native와 FireBase연동하기 (Android SetUp)

3. 파이어베이스 프로젝트에서 플렛폼을 추가함.

  3-1. 플렛폼을 추가할때 Android package name을 추가해야하는데 앱안에 있는 것과 같은 이름을 사용해야함 ./android/app/build.gradle에서 다음 부분을 찾아 ID 이름을 입력

defaultConfing{
  applicationId "id 이름"

 

  3-2. android nickname은 알아서 지어주고 Debug signing certificate SHA-1가 필요한데 이는 구글 인증을 하거나 핸드폰번호나 Dynamiv Link로 인증하고 싶다면 필요하다.

이를 하기 위해서 VS CODE로 돌아와 터미널에서 다음을 입력하면 터미널에서 Text가 나온다.

cd android && ./gradlew signingReport

그 후 Task :app:signingReport라는 걸 찾아주고 SHA1의 부분을 찾아 복사하고 파이어베이스에 붙어주면 파일을 다운받을 수 있는데 이 파일을 앱안에 넣어줘야한다.

 

4. 다음 버튼을 누르고 ./android/build.gradle에 가서 google()과 classpath() 부분을 확인해 주고 없는건 추가해준다.

  ./android/app/build.gradle에가서도 화면에 나와있는 부분을 추가해주어야한다.

 

5. npm run android를 해주어 잘 설치가 되었는지 확인한다.

 

React Native와 FireBase연동하기 (IOS SetUp)

3. 파이어베이스 프로젝트에 ios추가

  3-1. ios bundle ID를 입력해야하는 데 이는 XCode안에서 찾아야한다. 프로젝트 내의 ios폴더를 finder로 열어 .xcworkspace나 .xcodeproj 파일을 눌러 실행시킨다. Xcode에서 Pods 말고 프로젝트 이름의 폴더를 클릭하면 Identity에 Bundle Identifier가 있다. (xcode창은 끄지 말것).

app nickname은 원하는 걸 작성하면되고 app store ID는 앱스토어  이미 출시가됬다면 그 번호를 작성해주면 된다.

 

4. 다음 버튼을 누르고 기다리면 다운로드 해야할 파일이 나올것이다. 그 파일을 다운로드 하고 이 파일을 프로젝트에다 추가해야하는데 xcode에서  프로젝트로 가서 오른쪽클릭해서 add files to '프로젝트 명'을 누르고 다운받은 파일을 누르고 Copy items if needed , create groups 항목에 체크하고 add를 누른다.

 

5. ./ios/{projectName}/AppDelegate.mm file (or AppDelegate.m)을 열어주고 다음을 추가

#import <Firebase.h>

didFinishLaunchingWithOptions 라는 function을 찾아주고 

[FIRApp configure];

를 넣어준다. 넣을 수있는공간은 comment으로 넣으라고 써져있다.

쓰고 나서 다음을 터미널에 작성하여 실행

npx pod-install

그리고 Xcode 를 닫아주고 Use version on Disk 클릭해주고 프로젝트를 실행시켜 문제가 없는지 확인한다.

npm run ios

 

firebase의 기능을 사용하기 위해서는 각 기능들을 설치를 해줘야한다. 

728x90

+ Recent posts