===너의과학===/BE] Nestjs

[BE][Nestjs-A-02-02][공식문서로 공부하기:OVERVIEW_Controllers]

Homo knowledgian 2023. 6. 7. 21:24
728x90
반응형

=====================================================================
https://docs.nestjs.com/controllers
=====================================================================
[Controllers]
- Controllers are responsible for 
    handling incoming requests and returning responses to the client.
= Controllers는 incoming requests를 handling하고 
    clinet에 responses를 returning하는 역할을 한다.
- A controller's purpose is to receive specific requests 
    for the application.
= controller's purpose는 application에 specific requests을 receive한다.
- The routing mechanism controls which controller receives 
    which requests.
= routing mechanism은 which controller가 which requests를
    receives하는 지를 controls한다.
- Frequently, each controller has more than one route, 
    and different routes can perform different actions.
= 종종, each controller는 1개 이상의 route가 있고,
    different routes는 different actions을 수행할 수 있다.
- In order to create a basic controller, 
    we use classes and decorators.
= basic controller를 create하기 위해서, classes와 decorators를 사용한다.
- Decorators associate classes with required metadata 
    and enable Nest to create a routing map 
    (tie requests to the corresponding controllers).
= Decorators는 classes를 required metadata와 associate(연결)하고
    Nest가 routing map을 create할 수 있게 한다.
    (requests에 corresponding(해당)하는 controllers에 tie(연결))
- HINT
    For quickly creating a CRUD controller 
        with the validation built-in, 
        you may use the CLI's CRUD generator: 
        nest g resource [name].
= 힌트
    validation이 built-in된 CRUD controller를 quickly creating하려면,
    CLI's CRUD generator를 사용하면 된다.
    $ nest g resource [name]
=====================================================================
[Routing]
- In the following example we'll use the @Controller() decorator, 
    which is required to define a basic controller. 
= following example에서 basic controller를 define하는데 required되는
    @Controller() decorator를 사용한다.
- We'll specify an optional route path prefix of cats. 
= optional route path를 'cats'라는 prefix를 지정할 것이다.
- Using a path prefix in a @Controller() decorator allows us 
    to easily group a set of related routes, 
    and minimize repetitive code. 
= @Controller decorator에 prefix path를 사용하면 related routes set을
    easily group화하고 repetitive code를 minimize할 수 있다.
- For example, we may choose to group a set of routes 
    that manage interactions with a cat entity under the route /cats. 
= 예를 들어, "/cats" route 아래 cat entity와 interactions을 관리하는
    a set of routes로 group하도록 선택할 수 있다.
- In that case, 
    we could specify the path prefix cats 
    in the @Controller() decorator so that we don't have to repeat 
    that portion of the path for each route in the file.
= 이 경우에, file에 each route에 대한 path의 portion을 repeat할 필요가 없게
    @Controller() decorator에 'cats' prefix path를 specify할 수 있다.
- ex) cats.controller.ts
- HINT
    To create a controller using the CLI, 
    simply execute the $ nest g controller [name] command.
= 힌트
    CLI를 사용해서 controller를 create하기 위해서, simply
    "$ nest g controller [name]"를 실행하면 된다.
- The @Get() HTTP request method decorator 
    before the findAll() method tells Nest to create a handler 
    for a specific endpoint for HTTP requests.
= findAll() method 앞에 @Get() HTTP request method decorator는
    Nest에게 specific endpoint에 대한 HTTP requests용 handler를 생성하게 한다.
- The endpoint corresponds to the HTTP request method 
    (GET in this case) and the route path. 
= endpoint는 HTTP requests method(이 경우 GET)과 route path에 
    corresponds(해당)한다.
- What is the route path? 
= route path는 무엇인가?
- The route path for a handler is determined by concatenating 
    the (optional) prefix declared for the controller, 
    and any path specified in the method's decorator. 
= handler의 route path는 controller에 대해 declared된 (optional)한 prefix와
    method의 decorator에 specified any path로 concatenating(연결)하여
    determined된다.
- Since we've declared a prefix for every route (cats), 
    and haven't added any path information in the decorator, 
    Nest will map GET /cats requests to this handler. 
= every route(cats)에 대해 prefix를 declared되었고 decorator에 any path를
    added하지 않았기 때문에, Nest는 "GET /cats" requests를 handler에
    map 할 것이다.
- As mentioned, 
    the path includes both the optional controller path prefix 
    and any path string declared in the request method decorator. 
= mentioned한 것 처럼, path는 optional controller path prefix와
    request method decorator에 declared된 any path string이 모두 포함된다.
- For example, 
    a path prefix of cats combined with the decorator @Get('breed') 
    would produce a route mapping for requests like GET /cats/breed.
= 예를 들어, @Get('breed') decorator와 결합된 'cats' path prefix는
    'GET /cats/breed' 같은 requests에 route mapping을 produce합니다.
- In our example above, when a GET request is made to this endpoint, 
    Nest routes the request to our user-defined findAll() method. 
= example above에서, this endpoint에 GET request이 made될 때,
    Nest는 request를 user-defined findAll() method로 routes한다.
- Note that the method name we choose here is completely arbitrary. 
= here에 choose한 method name은 completely arbitrary(임의)적이다.
- We obviously must declare a method to bind the route to, 
    but Nest doesn't attach any significance to the method name chosen.
= obviously(분명히) route를 bind할 method를 declare해야 하지만,
    Nest는 chosen method name에 any significance(의미)도
    attach(부여)하지 않는다.
- This method will return a 200 status code 
    and the associated response, which in this case is just a string. 
= This method는 200 status code와 associated(관련) response을 
    return할 것이고, in this case string뿐이다.
- Why does that happen? 
= 무슨 일이 있어난 건가?
- To explain, we'll first introduce the concept 
    that Nest employs two different options 
    for manipulating responses:
= explain을 위해서, first(먼저) Nest는 response을 manipulating(조작)하기 위해
    two different options을 employs(사용)하는 concept을 introduce한다.
- Standard(recommended) : 
    Using this built-in method, 
        when a request handler returns a JavaScript object or array, 
        it will automatically be serialized to JSON. 
    When it returns a JavaScript primitive type 
        (e.g., string, number, boolean), however, Nest will send 
        just the value without attempting to serialize it. 
    This makes response handling simple: 
        just return the value, and Nest takes care of the rest.
    Furthermore, the response's status code is always 200 by default, 
        except for POST requests which use 201. 
    We can easily change this behavior 
        by adding the @HttpCode(...) decorator 
        at a handler-level (see Status codes(link)).
= Standard(recommended) :
    this built-in method를 사용하면, 
        resquest handler가 JavaScript object 또는 array을 return할 때,
        automatically JSON으로 serialized될 것이다.
    그러나 (예, string, number, boolean)같은 JavaScript primitive type을
        반환할때, Nest는 primitive type 값을 serialize하려 attempting 없이
        단지 value만 return한다.
    This(이렇게 하는 건) response handling(처리)가 simple해진다:
        단지 value를 return하면, Nest가 rest(나머지)를 처리한다.
    계다가, response's status code는 "201"을 사용하는 POST requests를 제외하고,
        항상 by default로 200이다.
    @HttpCode(...) decorator를 handler-level에서 adding하여
        this behavior(동작)을 easily change할 수 있다.
    (Status codes (link))
!link : https://docs.nestjs.com/controllers#status-code!
- Library-specific : 
    We can use the library-specific (e.g., Express) response object, 
        which can be injected using the @Res() decorator in the method 
        handler signature (e.g., findAll(@Res() response)). 
    With this approach, you have the ability 
        to use the native response handling methods 
        exposed by that object. 
    For example, with Express, 
        you can construct responses using code 
        like response.status(200).send().
= Library-specific :
    method handler signature(예로, findAll(@Res() response))에
        @Res() decorator를 사용하여 inject할 수 있는 
        library-specific(예, Express)한 response object를 사용할 수 있다.
    this approach로, that object에 exposed된 native response를
        handling methods를 사용할 수 있다.
    예를 들어, Express로, "response.status(200).send()" 같은 code를 사용해서
        response를 construct(구성)할 수 있다.
- WARNING
    Nest detects when the handler is using either @Res() or @Next(), 
        indicating you have chosen the library-specific option. 
    If both approaches are used at the same time, 
        the Standard approach is automatically disabled 
        for this single route and will no longer work as expected. 
    To use both approaches at the same time 
        (for example, 
        by injecting the response object to only set cookies/headers 
        but still leave the rest to the framework), 
    you must set the passthrough option 
        to true in the @Res({ passthrough: true }) decorator.
= 주의
    Nest는 handler가 @Res() 또는 @Next()를 using할 때를 detects해서,
        library-specific option을 chosen할 것을 indicating(나타)낸다.
    both approaches는 at the same time을 used된 경우라면,
        Standard approach은 this single route에 대해 
        automatically disable(비활성)화되어 expected(예상)대로는
        no longer(더 이상) work하지 않는다.
    both approaches가 at the same time에 use하기 위해서
        (예로, response object를 injecting하여 cookies/headers만 set하고
        rest(나머지)는 framework에 그대로 둔다.),
    @Res({ passthrough: true }) decorator에 passthrough option을
        true로 set해야 한다.
=====================================================================
[Request object]
- Handlers often need access to the client request details. 
= Handler는 종종 client request details에 access할 필요가 있다.
- Nest provides access to the request object 
    of the underlying platform (Express by default). 
= Nest는 (by default로 Express인) underlying(기본) platform의
    request object에 access(접근권한)을 provide한다.
- We can access the request object by instructing Nest to inject it 
    by adding the @Req() decorator to the handler's signature.
= handler's signature에 @Req() decorator를 adding해서
    Nest에 it(@Req~)를 inject하도록 instructing하여 request object에
    access 할 수 있다.
- ex) cats.controller.ts
- HINT
    In order to take advantage of express typings 
    (as in the request: Request parameter example above), 
    install @types/express package.
= 힌트
    typings으로 express를 이용하기 위해서
    (위 ex)에서 "request: Request" parameter 처럼),
    "@types/express" package를 설치해라.
- The request object represents the HTTP request 
    and has properties for the request query string, 
    parameters, HTTP headers, and body (read more here(link)). 
= request object는 HTTP request를 represents(나타)내고 
    request query string, parameter, HTTP headers, body(상세는 아래 링크)에
    대한 properties를 가진다.
!link : https://expressjs.com/en/api.html#req!
- In most cases, it's not necessary to grab these properties manually. 
= In most cases에 manually(수동으로) these properties(속성)들을
    grap(가져올) necessary(필요)는 없다.
- We can use dedicated decorators instead, such as @Body() or @Query(), 
    which are available out of the box. 
    !out of the box : 즉시 사용할 수 있는!
!link : https://m.blog.naver.com/yangseungjae/220708695668!
= 대신에 @Body() 또는 @Query() 같이 out of the box(즉시 사용)할 수 있는
    dedicated(전용)한 decorator를 사용할 수 있다.
- Below is a list of the provided decorators 
    and the plain platform-specific objects they represent.
= Below(아래엔) provided decorator와 they(decorators)가 represent하는
    plain(일반) platform-specific 목록이 있다.
- @Request(), @Req() : req
- @Response(), @Res()* : res
- @Next() : next
- @Session() : req.session
- @Param(key?: string) : req.params / req.params[key]
- @Body(key?: string) : req.body / req.body[key]
- @Query(key?: string) : req.query / req.query[key]
- @Headers(name?: string) : req.headers / req.headers[name]
- @Ip() : req.ip
- @HostParam() : req.hosts
- * For compatibility with typings across underlying HTTP platforms 
    (e.g., Express and Fastify), 
    Nest provides @Res() and @Response() decorators. 
= underlying(기본) HTTP platforms(e.g., Express and Fastify) across(간에)
    typings과 compatibility(호환성)을 위해,
    Nest는 @Res and @Response() decorators를 provides한다.
- @Res() is simply an alias for @Response(). 
= @Res()는 @Response()의 simply alias(별칭)이다.
- Both directly expose 
    the underlying native platform response object interface. 
= Both(@Res and @Response) underlying(기본) 
    native platfrom response object interface를 directly expose(노출)한다.
- When using them, 
    you should also import the typings for the underlying library 
    (e.g., @types/express) to take full advantage. 
= them(@Res and @Response)을 사용할 때, full(최대) advantage(이용)하려면
    underlying(기본) library(e.g., @types/express)를 typings해서
    import 해야한다.
- Note that when you inject either @Res() or @Response() 
    in a method handler, 
    you put Nest into Library-specific mode for that handler, 
    and you become responsible for managing the response. 
= method handler에 @Res() 또는 @Response()를 inject할 때,
    that handler(위~)에 대한 Library-specific mode로 Nest를 put하고,
    you는 response를 managing할 responsible이 become된다.
- When doing so, you must issue some kind of response 
    by making a call on the response object 
    (e.g., res.json(...) or res.send(...)), 
    or the HTTP server will hang.
= doing so할 때, (e.g., res.json(...) or res.send(...)) 같은 
    response object를 making a call함으로써 some kind of response을 issue
    해야하고 or(그러지 않으면) HTTP server는 will hang(중단)될 것이다.
- HINT
    To learn how to create your own custom decorators, 
        visit this chapter.
= 힌트
    your own custom decorators를 create하는 how to를 learn하기 위해서,
        this chapter(link)를 visit해라.
!link : https://docs.nestjs.com/custom-decorators!
=====================================================================
[Resources]
- Earlier, 
    we defined an endpoint to fetch the cats resource (GET route). 
= Earlier(이전에), 'cats' resource(GET route)를 fetch(가져오는)
    endpoint를 정의했다.
- We'll typically also want to provide an endpoint 
    that creates new records. 
= typically(일반적으로) new records를 create하는 endpoint도 provide하고 싶다.
- For this, let's create the POST handler:
= For this(이를 위해), POST handler를 create해 보자.
- ex) cats.controller.ts
- It's that simple. 
= It(create a POST handler)는 simple하다.
- Nest provides decorators for all of the standard HTTP methods: 
    @Get(), @Post(), @Put(), @Delete(), @Patch(), @Options(), 
    and @Head(). 
= Nest는 all of the standard HTTP methods에 대한 decorators를 제공한다.:
    @Get(), @Post(), @Put(), @Delete(), @Patch(), @Options(), @Head().
- In addition, @All() defines an endpoint that handles all of them.
= In addition(또한), @All()은 all of them(모든 decorators)를 handles하는
    endpoint로 정의된다.
=====================================================================
[Route wildcards]
- Pattern based routes are supported as well. 
= Pattern based routes도 as well(역시) supported 된다.
- For instance, the asterisk is used as a wildcard, 
    and will match any combination of characters.
= For instance, asterisk는 wildcard로 used되어
    any combination(어떤 조합)의 characters와도 match(일치)할 것이다.
- ex) @Get('ab*cd')
    findAll() {...}
- The 'ab*cd' route path will match abcd, ab_cd, abecd, and so on. 
= 'ab*cd' route path는 'abcd', 'ab_cd', 'abecd' 등등과 match(일치)될 것이다.
- The characters ?, +, *, and () may be used in a route path, 
    and are subsets of their regular expression counterparts. 
= '?', '+', '*', '()'는 route path에 사용되고,
    regular expression counterparts(해당 정규식)의 subsets이다.
- The hyphen (-) and the dot (.) are interpreted literally 
    by string-based paths.
= hyphen(-)과 dot(.)는 literally(문자 그대로) string-based paths로 해석된다.
=====================================================================
[Status code]
- As mentioned, the response status code is always 200 by default, 
    except for POST requests which are 201. 
= mentioned(언급했듯이), response status code는 201인 POST requests를
    제외하고 always 200이다.
- We can easily change this behavior 
    by adding the @HttpCode(...) decorator at a handler level.
= handler level에서 @HttpCode(...) decorator를 adding하여
    this behavior를 easily change할 수 있다.
- ex) @Post()
    @HttpCode(204)
    create() {...}
- HINT
    Import HttpCode from the @nestjs/common package.
= 힌트
    HttpCode package에서 @nestjs/common를 가져온다.
- Often, your status code isn't static but depends on various factors. 
= Often(종종), status code는 static하지 않고 various factors에 따라 달라진다.
- In that case, you can use a library-specific response 
    (inject using @Res()) object 
    (or, in case of an error, throw an exception).
= In that case, library-specific response(@Res()를 써서 inject) 
    object를 사용할 수 있다.(또는 in case of an error에 exception을 throw함).
=====================================================================
[Headers]
- To specify a custom response header, 
    you can either use a @Header() decorator 
    or a library-specific response object 
    (and call res.header() directly).
= custom response header를 specify하기 위해서,
    @Header() decorator 또는 library-specific response object를 
    사용할 수 있다. (그리고 바로 res.header()라고 부른다.)
- ex) @Post()
    @Header('Cache-Control', 'none')
    create() {...}
- HINT
    Import Header from the @nestjs/common package.
= 힌트
    @nestjs/common package에서 Header를 Import한다.
=====================================================================
[Redirection]
- To redirect a response to a specific URL, 
    you can either use a @Redirect() decorator 
    or a library-specific response object 
    (and call res.redirect() directly).
= response를 specific URL로 redirect하려면, @Redirect() decorator 또는
    library-specific response object를 use할 수 있다.
    (and res.rediect()를 directly call 한다.)
- @Redirect() takes two arguments, url and statusCode, 
    both are optional. 
= @Redirect()는 two arguments를 takes하고, url 그리고 statusCode는,
    둘다 optional이다.
- The default value of statusCode is 302 (Found) if omitted.
= statusCode의 default value는 omitted되었다면 302 (Found)이다.
- ex) @Get()
    @Redirect('https://nestjs.com', 301)
- Sometimes you may want to determine the HTTP status code 
    or the redirect URL dynamically. 
= Sometimes HTTP status code 또는 dynamically redirect URL을
    determine해야 할 수 있다.
- Do this by returning an object from the route handler method 
    with the shape:
= route handler method에서 with the shape로 object를 returning해서
    this를 수행한다.
- ex) { "url": string, "statusCode": number }
- Returned values will override any arguments passed 
    to the @Redirect() decorator. For example:
= Returned values는 @Redirect() decorator에 passed된 any arguments를
    override할 것이다. For example:
- ex) @Get('docs')
    @Redirect('https://docs.nestjs.com', 302)
    getDocs(@Query('version') version) {
        if (version && version === '5') {
            return { url: 'https://docs.nestjs.com/v5/' };
        }
    }
=====================================================================
[Route parameters]
- Routes with static paths won't work when you need to 
    accept dynamic data as part of the request 
    (e.g., GET /cats/1 to get cat with id 1). 
= (e.g., GET /cats/1 to get cat with id 1)같이 request의 part(일부)로
    dynamic data를 accept할 필요가 있는 때 static paths로
    Routes는 won't work한다.
- In order to define routes with parameters, 
    we can add route parameter tokens in the path of the route 
    to capture the dynamic value at that position in the request URL. 
= parameter로 routes를 define하기 위해서,
    path of the route에 route parameter tokens을 adding해서
    request URL에 that position에 dynamic value를 capture할 수 있다.
- The route parameter token in the @Get() decorator example 
    below demonstrates this usage. 
= @Get() decorator example에 route parameter token은
    below(아래에) this usage(사용법)을 demonstrates(보여)준다.
- Route parameters declared in this way can be accessed 
    using the @Param() decorator, 
    which should be added to the method signature.
= Route parameters는 this way로 method signature에 의해 added되어야 하는
    @Param() decorator를 using해서 accessed 될 수 있다.
- HINT
    Routes with parameters should be declared after any static paths. 
    This prevents the parameterized paths 
        from intercepting traffic destined for the static paths.
= 힌트
    Route with parameters는 any static paths after(다음에) 
        declared되어야 한다.
    This(위~)은 parameterized path가 static paths로 destined(향하는)
        traffic을 intercepting하는 것을 prevents한다.
- ex) @Get(':id')
    findOne(@Param() params: any): string {
        console.log(params.id);
        return `This action returns a #${params.id} cat`;
    }
- @Param() is used to decorate a method parameter 
    (params in the example above), 
    and makes the route parameters available as properties of 
    that decorated method parameter inside the body of the method.
= @Param()은 method parameter를 (위 예시의 params) decorate하는데
    used될 수 있어서, 
    route parameters를 the body of the method inside(안에서)
    decorated method parameter의 properties로 available하게 한다.
- As seen in the code above, 
    we can access the id parameter by referencing params.id. 
= code above에서 보듯이, id parameter는 params.id를 referencing해서
    access할 수 있다.
- You can also pass in a particular parameter token to the decorator, 
    and then reference the route parameter directly 
    by name in the method body.
= particular parameter token을 to the decorator에 pass한 다음,
    method body에 name으로 route parameter를 directly reference할 수 있다.
- HINT
    Import Param from the @nestjs/common package.
= 힌트
    @nestjs/common package에서 Param을 Import해야 한다.
- ex) @Get(':id')
    findOne(@Param('id') id: string): string {
        return `This action returns a #${id} cat`;
    }
=====================================================================
[Sub-Domain Routing]
- The @Controller decorator can take a host option to require 
    that the HTTP host of the incoming requests 
    matches some specific value.
= @Controller decorator는 incoming request의 HTTP host가 
    specific value와 match(일치)하도록 require(요구)하는 
    host option을 take할 수 있다.
- ex) @Controller({ host: 'admin.example.com' })
    export class AdminController {
        @Get()
        index(): string {
            return 'Admin page';
        }
    }
- WARNING
    Since Fastify lacks support for nested routers, 
    when using sub-domain routing, 
    the (default) Express adapter should be used instead.
= 경고
    Fastify는 nested routers에 대한 support이 lacks하므로,
    sub-domain routing을 using할 때,
    (default) Express adapter를 instead(대신) used(사용되어야) 한다.
- Similar to a route path, 
    the hosts option can use tokens to capture the dynamic value 
    at that position in the host name. 
= route path와 Similar하게, hosts option은 tokens 사용해서 dynamic value를
    host name에 that position에 capture할 수 있다.
- The host parameter token 
    in the @Controller() decorator example below 
    demonstrates this usage. 
= below @Controller decorator example에서 host parameter token은
    this usage(@Controller())를 demonstrates(보여)준다.
- Host parameters declared in this way 
    can be accessed using the @HostParam() decorator, 
    which should be added to the method signature.
= this way로 declared된 Host parameters는 method signature에 added해야 하는
    @HostParam() decorator를 사용해서 accessed될 수 있다.
- ex) @Controller({ host: ':account.example.com' })
    export class AccountController {
        @Get()
        getInfo(@HostParam('account') account: string) {
            return account;
        }
    }
=====================================================================
[Scopes]
- For people coming from different programming language backgrounds, 
    it might be unexpected to learn that in Nest, 
    almost everything is shared across incoming requests. 
= different programming language backgrounds에서 coming한 people에게,
    Nest에서 almost everything은 incoming reuqests에서 shared된거라는 것을
    learn(알) 게 되는 것을 unexpected(기대하지 못)할지 모른다.
- We have a connection pool to the database, 
    singleton services with global state, etc. 
= database에 대한 connection pool, 
    global state의 singleton services 등이 있다.
- Remember that Node.js doesn't follow the request/response 
    Multi-Threaded Stateless Model 
    in which every request is processed by a separate thread. 
= Node.js는 every request가 separate(별도의) thread에서 processed(처리)되는
    request/response Multi-Threaded Stateless Model을 follow하지 않음을
    Remember해라.
- Hence, using singleton instances is fully safe for our applications.
= 따라서, singleton instance를 using것은 application에 fully safe하다.
- However, there are edge-cases when request-based lifetime 
    of the controller may be the desired behavior, 
    for instance per-request caching in GraphQL applications, 
    request tracking or multi-tenancy. 
= However, for instance로 GraphQL applications의 
    pre-request(요청별) caching, request tracking 또는 multi-tenancy같은
    the controller의 request-based lifetime이 desired(원하는) behavior일 수
    있는 edge-cases(극단적인 경우)가 있다.
- Learn how to control scopes here.
= here(link)에서 scopes를 control하는 how to를 learn해보자.
!link : https://docs.nestjs.com/support!
=====================================================================
[Asynchronicity]
- We love modern JavaScript and we know 
    that data extraction is mostly asynchronous. 
= We는 modern JavaScript를 love하고 
    data extraction이 mostly asynchronous(비동기식)이라는 것을 know한다.
- That's why Nest supports and works well with async functions.
= That(위~)이 Nest가 async functions을 supports하고 works well하는 why다.
- HINT
    Learn more about async / await feature here(link).
= 힌트
    here(link)에서 async / await feature에 대해 learn해보자.
!link : https://kamilmysliwiec.com/typescript-2-1-introduction-async-await!
- Every async function has to return a Promise. 
= Every async function은 Promise를 return 해야한다.
- This means that you can return a deferred value 
    that Nest will be able to resolve by itself. 
= This(위~)은 Nest가 by itself(자체로) resolve(해결)할 수 있는 deferred(지연된)
    value를 return 할 수 있다는 것을 means(의미)한다.
- Let's see an example of this:
= this(위~)에 대한 example을 살펴보자.
- ex) cats.controller.ts
    @Get()
    async findAll(): Promise<any[]> {
        return [];
    }
- The above code is fully valid. 
= above code는 fully valid(유효)하다.
- Furthermore, Nest route handlers are even more powerful 
    by being able to return RxJS observable streams. 
= Furthermore(또한), Nest route는 handlers는 RxJS observable stream을
    return 할수 있으므로 more powerful하다.
- Nest will automatically subscribe to the source underneath 
    and take the last emitted value (once the stream is completed).
= Nest는 automatically underneath(아래)의 source를 subscribe(변화를 바라)보고
    the last(마지막)으로 emitted(방출)된 value을 take한다.
    (once(일단) stream이 completed되면)
- ex) cats.controller.ts
    @Get()
    findAll(): Observable<any[]> {
        return of([]);
    }
- Both of the above approaches work and you can use 
    whatever fits your requirements.
= above(위) Both approaches(방식)들은 work하며 requirements에 fits(맞는) 것을
    use 할 수 있다.
=====================================================================
[Request payloads]
- Our previous example of the POST route handler didn't accept 
    any client params. 
= POST route handler의 previous example는 client params를 accept하지 않는다.
- Let's fix this by adding the @Body() decorator here.
= here에 @Body decorator를 adding해서 this(위~문제)를 fix(해결)해보자.
- But first (if you use TypeScript), 
    we need to determine the DTO (Data Transfer Object) schema. 
= But first(먼저)(TypeScript를 use한다면), DTO schema를 determine해야 한다.
- A DTO is an object that defines how the data 
    will be sent over the network.     
= DTO는 data가 network를 over해서 how(어떻게) be sent될 것인지 defines하는
    object이다.
- We could determine the DTO schema by using TypeScript interfaces, 
    or by simple classes. 
= TypeScript interface나 simple classes를 using해서 DTO schema를 
    determine(정)할 수 있다.
- Interestingly, we recommend using classes here. 
= Interestingly, here에 classes를 using하는 걸 recommend한다.
- Why? Classes are part of the JavaScript ES6 standard, 
    and therefore they are preserved as real entities 
    in the compiled JavaScript. 
= Why? Classes는 JavaScript ES6 standard의 part로, 
    compiled JavaScript에 real entities로 preserved(보존)된다.
- On the other hand, 
    since TypeScript interfaces are removed during the transpilation, 
    Nest can't refer to them at runtime. 
= On the other hand(반면에), TypeScript interfaces는 transpilation(변환) 중
    removed(제거)되기 때문에, Nest는 runtime에 them(이)를 refer(참조)할 수 없다.
- This is important because features such as Pipes 
    enable additional possibilities 
    when they have access to the metatype of the variable at runtime.
= Pipes 같은 features가 runtime시 variable의 metatype에 access할 때
    additional possibilities를 enable(가능)하게 하기 때문에 important한다.
- Let's create the CreateCatDto class:
= CreateCatDto class를 생성해 보자:
- ex) create-cat.dto.ts
- It has only three basic properties. 
= three baisc properties(속성) only(만) 있다.
- Thereafter we can use the newly created DTO 
    inside the CatsController:
= Thereafter(그런다음) newly(새롭게) created(생성된) DTO를 
    CatsController inside(내부에서) use할 수 있다.
- ex) cat.controller.ts
- HINT
    Our ValidationPipe can filter out properties 
    that should not be received by the method handler. 
    In this case, we can whitelist the acceptable properties, 
    and any property not included in the whitelist 
    is automatically stripped from the resulting object. 
    In the CreateCatDto example, our whitelist is the name, age, 
    and breed properties. Learn more here.
= 힌트
    ValidationPipe는 method handler에서 be received(수신)되어선 안되는
        properties(속성)을 filter할 수 있다. 
    In this case, 
        acceptable(허용가능한) properties을 whitelist에 넣을 수 있고,
        whitelist에 included(포함)되지 않은 any property는 
        resulting object에서 automatically stripped(제거)된다.
    CreateCatDto 예제에서, whitelist는 name, age, bread properties이다.
    here(아래 링크)에서 자세히 알아보세요.
!https://docs.nestjs.com/techniques/validation#stripping-properties!
=====================================================================
[Handling errors]
- There's a separate chapter about handling errors 
    (i.e., working with exceptions) here(link).
= here(아래 링크)에 errors handling(i.e., exceptions 작업)에 대한
    separate(별도)의 chapter가 있다.
!link : https://docs.nestjs.com/exception-filters!
=====================================================================
[Full resource sample]
- Below is an example that makes use of several 
    of the available decorators to create a basic controller. 
= Below는 basic controller를 create하기 위해 
    several(몇몇)의 available한 decorators를 make use(사용)한 example이다.
- This controller exposes a couple of methods to access 
    and manipulate internal data.
= This controller는 internal data에 access하고 manipulate하는
    a couple of(몇몇) method를 exposes(제공)한다.
- ex) cats.controller.ts
- HINT
    Nest CLI provides a generator (schematic) 
    that automatically generates all the boilerplate code 
    to help us avoid doing all of this, 
    and make the developer experience much simpler. 
    Read more about this feature here(link).
= 힌트
    Nest CLI는 all the boilerplate(상용구) code를 automatically
        generates(생성)하는 generator(schematic(도식))를 provides하여
        all of this(이 모든 작업)을 avoid하고,
        developer가 much simpler(더 간단하게) experience(경험)하게 한다.
    here(아래 링크)에 this feature에 대해 Read해라.
!link : https://docs.nestjs.com/recipes/crud-generator!
=====================================================================
[Getting up and running]
- With the above controller fully defined, 
    Nest still doesn't know that CatsController exists 
    and as a result won't create an instance of this class.
= above controller가 fully defined된 With(채로),
    Nest는 still(여전히) CatsController가 exists(존재)하는지 모르므로
    and(그래서) as a result(결과)로서 this class의 instance를 create하지
    않는다.
- Controllers always belong to a module, 
    which is why we include the controllers array 
    within the @Module() decorator. 
= Controllers는 always module에 belong해서, @Module() decorator 내에
    controllers array에 include(포함)되게 된다.    
- Since we haven't yet defined any other modules 
    except the root AppModule, 
    we'll use that to introduce the CatsController:
= we는 yet(아직) the root AppModule을 except하고는 any other modules을
    defined하지 않았기 때문에, CatsController를 introduce를 할 것이다.
- ex) app.module.ts
    import { Module } from '@nestjs/common';
    import { CatsController } from './cats/cats.controller';

    @Module({
        controllers: [CatsController],
    })
    export class AppModule {}
- We attached the metadata to the module class 
    using the @Module() decorator, 
    and Nest can now easily reflect 
    which controllers have to be mounted.    
= @Module() decorator를 using해서 module class에 metadata로 attached했고,
    and(이제) Nest가 be mounted되어야할 controllers를 
    easily reflect할 수 있다.
=====================================================================
[Library-specific approach]
- So far we've discussed the Nest standard way 
    of manipulating responses. 
= So far(지금까지) responses를 manipulating(조작)하는 
    Nest standard way에 대해 discussed(논의)했다.
- The second way of manipulating the response is 
    to use a library-specific response object. 
= response를 manipulating하는 second way은
    library-specific response object를 use(사용)하는 것이다.
- In order to inject a particular response object, 
    we need to use the @Res() decorator. 
= particular response object를 inject하기 위해서, 
    @Res() decorator를 use할 need가 있다.
- To show the differences, 
    let's rewrite the CatsController to the following:
= differences(차이점)을 show하기 위해서, the following(아래)에 
    CatsController를 rewrite해보자.
- ex) 
    import { Controller, Get, Post, Res, HttpStatus } from '@nestjs/common';
    import { Response } from 'express';

    @Controller('cats')
    export class CatsController {
        @Post()
        create(@Res() res: Response) {
            res.status(HttpStatus.CREATED).send();
        }

        @Get()
        findAll(@Res() res: Response) {
            res.status(HttpStatus.OK).json([]);
        }
    }
- Though this approach works, and does in fact allow for 
    more flexibility in some ways by providing full control 
    of the response object 
    (headers manipulation, library-specific features, and so on), 
    it should be used with care. 
= this approach(접근) works(방식)을 Though(통해), 그리고 in fact(실제로)
    response object(headers 조작, library-specific 기능, 등)의 
    full control(전체 제어)를 providing(제공)해서
    some ways(방식)으로 more flexibility(유연성)을 allow한다
    다만 with care(주의해서) be used(사용되어야) 한다.
- In general, the approach is much less clear 
    and does have some disadvantages. 
= In general(일반적으로), approach(접근 방식)은 much less(훨씬 덜) clear하고
    some disadvantages(몇 단점)을 가진다.
- The main disadvantage is that your code becomes platform-dependent 
    (as underlying libraries may have different APIs 
        on the response object), 
    and harder to test (you'll have to mock the response object, etc.).
= main disadvantages는 code가 platform-dependent(플랫폼에 따라 달라지게)되고
    (underlying(기본) libraries가 
    response object에 different APIs를 가질수 있다)
    test(response object 등을 mock(모의)하게 된다)하기 harder하다.
- Also, in the example above, 
    you lose compatibility with Nest features 
    that depend on Nest standard response handling, 
    such as Interceptors and @HttpCode() / @Header() decorators. 
= 또한, above example에서, 
    Interceptors 및 @HttpCode() / @Header() decorators와 같은
    Nest standard response handling(처리)에 depend on(의존)하는
    Nest features과 compatibility(호환성)이 lose(손실)된다.
- To fix this, you can set the passthrough option to true, as follows:
= this(위~)를 fix(해결)하기 위해서, as follows(아래 같이), passthrough option을
    true로 set할 수 있다.
- ex) @Get()
    findAll(@Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        return [];
    }
- Now you can interact with the native response object 
    (for example, 
    set cookies or headers depending on certain conditions), 
    but leave the rest to the framework.
= Now(이제) native(기본) response object와 interact할 수 있지만
    (for example, certain conditions에 depending on(따라) 
        cookies 또는 headers를 set한다 )
    rest(나머지)는 framework에 leave(위임)한다.
=====================================================================

https://github.com/yigongyikong/nestjs_official_docs/blob/officialDocs/docs.nestjs.com/02_02_OVERVIEW_Controllers.txt

 

GitHub - yigongyikong/nestjs_official_docs

Contribute to yigongyikong/nestjs_official_docs development by creating an account on GitHub.

github.com

 

[P.S. 잘못된 부분이나 이해하기 어려운 부분이 있다면, 댓글 남겨주시기 바랍니다.]

반응형