24 Oct 2020 |
Backend
Nestjs 튜토리얼 따라하기 2편
Controllers

- Controller는 서버 어플리케이션을 위하여 특정 요청을 받아들이는 역할을 한다.
- Controller를 만들기 위하여 클래스와 데코레이터를 사용
- 데코레이터는 요청을 해당 Controller에 연결한다.
# scr폴더 내에 cats폴더 생성
nest g controller cats
위 명령어를 이용하여 프로젝트를 생성하면 다음과 같은 구조를 가진다.
├── src
│ ├── app.controller.ts
│ ├── app.module.ts
│ ├── main.ts
│ └── cats
│ └── cats.controller.ts
cats.controller.ts에 다음과 같은 코드를 입력한다.
// src/cats/cats.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll() : string {
return 'This action returns all cats';
}
}
이후 http://localhost:3000/cats/ 에 접속

@Controller(‘cats’) 데코레이터로 인하여 CatsController에 연결되었고 GET method로 연결하였기 때문에 @Get() 데코레이터가 붙어있는 findAll() 함수가 실행된 모습을 볼 수 있다.
cats.controller.ts를 다음과 같이 수정한다.
// src/cats/cats.controller.ts
import { Controller, Get, Param, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
@Get(':id')
find(@Param('id')id) {
return id;
}
}
이후 http://localhost:3000/cats/1 에 접속

위의 find()함수와 같이 사용하면 파라미터도 같이 넘길 수 있다.
cats.controller.ts를 다음과 같이 수정한다.
// src/cats/cats.controller.ts
import { Controller, Get, HttpCode, Param, Post, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Post()
@HttpCode(200)
create(): string {
return 'This action adds a new cat';
}
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
@Get(':id')
find(@Param('id') id) {
return id;
}
}
POST method로 request를 전송해보자.

정상적으로 create() 함수가 실행되었다.
cats.controller.ts를 다음과 같이 수정한다.
// src/cats/cats.controller.ts
import { identifier } from '@babel/types';
import { Body, Controller, Get, Param, Post, Put, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Post()
create(@Body('name') name) {
return { name };
}
@Put()
update(@Body('id') id, @Body('name') name) {
return { id, name };
}
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
@Get(':id')
find(@Param('id') id) {
return id;
}
}

PUT method로 id 와 name을 파라미터로 하여 request를 날리고 그 결과 정상적으로 update()함수가 실행 되었다.
18 Oct 2020 |
PS
AtCoder Beginner Contest 180 D번 Takahashi Unevolved
문제
https://atcoder.jp/contests/abc180/tasks/abc180_d

풀이
타카하시를 진화시키지 않으면서 경험치를 최대로 얼마까지 쌓을 수 있는지 구하는 문제이다.
Kakomon Gym 으로 가면 힘이 A배오르고 AtCoder Gym 으로 가면 힘이 B오르고 공통적으로 1의 경험치를 얻는다.
최초 힘 스탯 X에서 A배가 B보다 적을 때 까지 A배를 하다가 B가 A배보다 적어지는 순간 B를 계속 선택하면 최대의 경험치를 획득할 수 있다.
단순하게 이를 구현하면 정답
코드
#pragma warning(disable : 4996)
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef tuple<ll,ll,ll> tl3;
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define rep(i, n) FOR(i, 0, n)
#define repn(i, n) FORN(i, 1, n)
#define tc(t) while (t--)
// https://atcoder.jp/contests/abc180/tasks/abc180_d
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll x,y,a,b;
cin >> x >> y >> a >> b;
ll ans = 0;
while(x<y/a && x*a<x+b){
ans++;
x *= a;
}
ans+=(y-1-x)/b;
cout << ans;
return 0;
}
18 Oct 2020 |
PS
AtCoder Beginner Contest 180 C번 Cream puff
문제
https://atcoder.jp/contests/abc180/tasks/abc180_c

풀이
정수 n이 주어졌을 때 n을 나눌 수 있는 모든 수를 출력하는 문제
n의 범위가 10^12 이하이므로 O(n)으로 풀면 시간초과가 뜬다.
이를 줄여주기만 하면 바로 해결 가능하다.
코드
#pragma warning(disable : 4996)
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef tuple<ll,ll,ll> tl3;
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define rep(i, n) FOR(i, 0, n)
#define repn(i, n) FORN(i, 1, n)
#define tc(t) while (t--)
// https://atcoder.jp/contests/abc180/tasks/abc180_c
vll v;
void getDivisors(ll n)
{
for (ll i = 1; i*i <= n; i++) {
if(i*i == n) v.push_back(i);
else if(n % i == 0){
v.push_back(i);
v.push_back(n/i);
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n;
cin >> n;
getDivisors(n);
sort(all(v));
for(auto k : v) cout << k << "\n";
return 0;
}
18 Oct 2020 |
PS
AtCoder Beginner Contest 180 B번 Various distances
문제
https://atcoder.jp/contests/abc180/tasks/abc180_b

풀이
n개의 정수 포인트가 주어졌을 때 맨하탄 거리, 유클리드 거리, 체비쇼프 거리를 각각 구하는 문제
각 거리의 공식은 문제에 적혀있으므로 그대로 구현하면 된다.
코드
#pragma warning(disable : 4996)
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef tuple<ll,ll,ll> tl3;
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define rep(i, n) FOR(i, 0, n)
#define repn(i, n) FORN(i, 1, n)
#define tc(t) while (t--)
// https://atcoder.jp/contests/abc180/tasks/abc180_b
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n;
cin >> n;
ll Manhattan = 0;
ld Euclidian = 0;
ll Chebyshev = 0;
rep(i,n){
ll e;
cin >> e;
e = abs(e);
Manhattan += e;
Chebyshev = max(Chebyshev, e);
Euclidian += (e*e);
}
Euclidian = sqrt(Euclidian);
cout << fixed;
cout.precision(15);
cout << Manhattan << "\n";
cout << Euclidian << "\n";
cout << Chebyshev << "\n";
}
18 Oct 2020 |
PS
AtCoder Beginner Contest 180 A번 box
문제
https://atcoder.jp/contests/abc180/tasks/abc180_a

풀이
너무 간단한 산수 문제
문제를 잘 읽으면 바로 풀 수 있는 문제.
코드
#pragma warning(disable : 4996)
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
typedef tuple<ll,ll,ll> tl3;
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define rep(i, n) FOR(i, 0, n)
#define repn(i, n) FORN(i, 1, n)
#define tc(t) while (t--)
// https://atcoder.jp/contests/abc180/tasks/abc180_a
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n,a,b;
cin >> n >> a >> b;
cout << n - a + b;
}