기본 콘텐츠로 건너뛰기

vulcanJS - 7. Posts 쓰기

이번엔 아주 간단합니다.
왜냐면 Posts 쓰기를 할 것이고 우리는 SmartForms를 이용해서 끝낼려고 하거든요.

Component를 또 만듭시다.
이름은 PostsNewComponent가 좋겠군요.
$ vulcan g component
? Package name spectrum-simplebb
? Component name PostsNewComponent
? Component type Class Component
? Register component Yes
   create packages/spectrum-simplebb/lib/components/PostsNewComponent.jsx
 conflict packages/spectrum-simplebb/lib/components/index.js
? Overwrite packages/spectrum-simplebb/lib/components/index.js? overwrite
    force packages/spectrum-simplebb/lib/components/index.js
이제 다 할 줄 아시죠?
vulcan g component 를 써서 진행합니다.
HomeComponent.jsx 에도 추가해야겠네요.
import React, { Component } from 'react';
import { registerComponent, Components } from 'meteor/vulcan:core';
class HomeComponent extends Component {
  render () {
    return (
      <div>
        Find me at packages/spectrum-simplebb/lib/components/HomeComponent.jsx
        <Components.PostsListComponent />
        <Components.PostsNewComponent />
      </div>
    );
  }
}
registerComponent('HomeComponent', HomeComponent);
export default HomeComponent;
이렇게 <Components.PostsNewComponent /> 한 줄 넣어줍니다.
Find me at packages/spectrum-simplebb/lib/components/HomeComponent.jsx
first thing
Find me at packages/spectrum-simplebb/lib/components/PostsNewComponent.jsx
브라우저에서 보면 PostsNewComponent.jsx가 잘 등록이 되있네요.
이제 Posts 입력 Form을 넣어봅시다.
http://docs.vulcanjs.org/forms.html 내용을 보면서 package.js 에 vulcan:forms를 추가합니다.
플러그인처럼 필요한 기능을 넣으면 되어서 편리합니다.
Package.describe({
  name: 'spectrum:simplebb',
});
Package.onUse((api) => {
  api.use([
    'vulcan:core',
    'vulcan:forms'
  ]);
  api.mainModule('lib/server/main.js', 'server');
  api.mainModule('lib/client/main.js', 'client');
});
가끔 package가 추가 안되는 경우가 있는데 meteor add vulcan:forms 후 meteor remove vulcan:forms 해서 넣다 빼 봅시다.
아무래도 버그(https://github.com/meteor/meteor/issues/7721)인 것 같습니다. 부디 다음버전에서 개선이 되길.


먼저 import Posts from  "../modules/posts/collection.js" 를 가져오고 vulcan의 Components 객체도 가져옵니다.
        <Components.SmartForm collection={Posts} />
한 줄만 넣어봅시다. PostsNewComponents.jsx는 이렇게 되겠지요.
import React, { Component } from 'react';
import { registerComponent, Components } from 'meteor/vulcan:core';
import Posts from  "../modules/posts/collection.js"
class PostsNewComponent extends Component {
  render () {
    return (
      <div>
        <Components.SmartForm collection={Posts} />
      </div>
    );
  }
}
registerComponent('PostsNewComponent', PostsNewComponent);
export default PostsNewComponent;
이제 브라우저 화면을 봅시다.
오오. Title과 Body가 생겼고 입력창도 보입니다.
뭔가 넣어봅시다.

이거슨 매직
입력하고 submit 누르면...?

!?!!!

들어갔습니다!
아니 뭐 이렇게 간단해도 되는 건가 싶은데 내부는 꽤 복잡합니다.
Collection2 + autoform + graphQL + react 까지 모두 합쳐서 이런 결과를 잘도 만들었네요.

해놓고 보니 다 좋은데 Body는 여러줄을 입력받고 싶습니다.
http://docs.vulcanjs.org/forms.html 내용을 읽어보니 
Support for basic form controls (input, textarea, radio, etc.).
이런 내용이 있습니다.
예제를 보니 schema에서 control 이라는 속성을 추가할 수 있나보네요.
./lib/modules/posts/schema.js 를 열어봅시다.
중간쯤 (아마 31라인 근처)
    title : {
   label: 'Title' ,
  type: String,
  optional: false,
  viewableBy: ['guests'],
  insertableBy: ['members'],
  editableBy: ['members'],
},

  
    body : {
   label: 'Body' ,
  type: String,
  optional: true,
  viewableBy: ['guests'],
  insertableBy: ['members'],
  editableBy: ['members'],
},
title과 body 속성을 이렇게 삐뚤삐뚤하게 자동 생성을 해놓았군요.
  control: 'text' 와 control: 'textarea' 를 각각 추가해봅시다.
schema.js 전체는 이렇겠지요.
const schema = {
  // default properties
  _id: {
    type: String,
    optional: true,
    viewableBy: ['guests'],
  },
  createdAt: {
    type: Date,
    optional: true,
    viewableBy: ['guests'],
    onInsert: (document, currentUser) => {
      return new Date();
    }
  },
  // userId: {
  //   type: String,
  //   optional: true,
  //   viewableBy: ['guests'],
  //   resolveAs: {
  //     fieldName: 'user',
  //     type: 'User',
  //     resolver: (movie, args, context) => {
  //       return context.Users.findOne({ _id: movie.userId }, { fields: context.Users.getViewableFields(context.currentUser, context.Users) });
  //     },
  //     addOriginalField: true
  //   }
  // },
 
    title : {
   label: 'Title' ,
  type: String,
  control: 'text',
  optional: false,
  viewableBy: ['guests'],
  insertableBy: ['members'],
  editableBy: ['members'],
},
 
    body : {
   label: 'Body' ,
  type: String,
  control: 'textarea',
  optional: true,
  viewableBy: ['guests'],
  insertableBy: ['members'],
  editableBy: ['members'],
},
 
};
export default schema;
다시 화면을 봅니다.
오오 TextArea가 나왔군요.

멀티라인!

멀티 라인을 입력할 수 있네요.
내용이 잘 들어갔는지 graphiQL(http://localhost:3000/graphiql)에서 한번 확인해볼까요? 절대 Component에서 화면에 보이게 구현하는게 귀찮아서 그러는게 아닙니다. 연습연습~ 자동완성으로 착착 입력합시다.
{
  PostsList(terms:{}) {
    _id
    createdAt
    title
    body
  }
}
로 검증해 봅니다.

\n로 구분한 멀티라인까지 잘 들어간 것을 확인할 수 있습니다.
꽤 편리하지요?
거의 다 왔습니다. 세부 조회, 수정이랑 삭제 정도만 하면 한 바퀴 다 돌아볼 것 같습니다.
용기를 잃지말고 계속 Meteor 고고! Vulcan 고고!

댓글

이 블로그의 인기 게시물

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.o...

Renoise로 바닥부터 Sound Design (No Sample/No VST)

Renoise는 Ableton Live Standard 버전처럼 기본적으로 아무 악기가 없고 달랑 샘플러 하나가 전부인데 그마나 다행인건 멀티레이어라고나 할까. 샘플러만 있으면 사실 다 되지. 아날로그 웨이브 테이블을 최소단위로 넣어서 루프를 돌리면  되니까. 근데 그러면 무조건 폴리포니가 되어서 구조적으로 모노 신스는 구현이 불가능하다. 그것도 방법이 없는 건 아닌데 Bend 라든가 Glide 등등으로 하면 되니까. 그래도 모노 신스가 있었으면 좋겠는데 방법이 있더라. http://forum.renoise.com/index.php?/topic/27225-renoise-native-monophonic-synthesiser/  이 글을 보고 약간 충격을 받음. 이펙터만 있으면 역시 소리를 만들 수 있구나! 바로 시도에 들어감. 처음은 이런 상태. 나는 누군가. 여긴 어딘가. 키보드를 눌러도 아무 소리가 안난다. ESC 눌러서 첫번째 트랙 맨위에 Z(C-4 00) 하나 눌러 놓고 일단 플레이. 일단 이렇게 해놓고 소리가 날 수 있게 한단 말이지. 그럼 먼저 제네레이터. 일단 1byte짜리라도 뭐가 있어야 시작을 할 수 있으니 빈 샘플을 만들자. 1byte 짜리 빈 샘플을 만든다. 당연히 소리가 안난다. DC Offset을 만들어 00 인 상태를 바꿔보자. 퍽하고 클릭음이 생기면서 Master Scope 에 변화가 생겼다. Meter도 생겼다. 그런데 이건 소리라고 할 수 없다. RingMod(Ring Modulator)를 추가해보자. 오오 소리가 난다. 0인 경우엔 Ring Modulator를 적용해도 0으로 소용이 없지만 DC Offset으로 값을 변경한 후부터 Oscillator에 따라 파형이 생긴다. 기본적으로 440Hz의 음을 들을 수 있다. 무에서 유를 만들기는 했는데 Pitch도 Volume도 없다. 일단 Pitch부터 해보자. Key Tracker로 Dest...

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면 ...