기본 콘텐츠로 건너뛰기

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 고고!

댓글

이 블로그의 인기 게시물

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/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.