기본 콘텐츠로 건너뛰기

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 접속해제 - 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...

느려터진 안드로이드 에뮬은 버리고 VM을 쓰자.

iOS개발 환경이 안드로이드보다 우월점은 여러가지가 있겠지만 개인적으로 가장 큰부분이라고 생각하는 점이 iOS Simulator 의 넘사벽 속도다. 사실 iOS 의 경우 Emulator 가 아니라 Simulator 라는 훼이크를 써서 그런건데. 하드웨어+소프트웨어를 같이 하는 회사만이 쓸 수 있는 필살기라 볼 수 있다. 반면 안드로이드의 경우 ARM 에뮬레이터를 사용하는데 이게 참 못만들었다. 플스에뮬이나 GBA에뮬 반정도만 만들어도 써줄텐데 아직 갈길이 멀다. 그래서 구시렁 거리면서 하드웨어를 연결해서 테스트를 하고 있는데 역시 USB연결하는 건 불편하고 apk 를 전송하는 과정도 그다지 빠르지 않아서 개발 생산성이 월등히 나아지지는 않는다. 루팅을 하면 wifi 를 통해 apk 를 인스톨 할 수 있다고 해서 몇 가지를 해보았으나 잘 모르겠지만 인스톨까진 잘 되었는데 디버깅 모드로 실행이 되지 않아 그만두었다. 게다가 전송속도도 USB보다 wifi가 느리고 맘에 들지 않더라. 그러던중 stackoverflow.com(늘 신세지고 있습니다) 에서 "VM으로 안드로이드를 띄워서 adb connect 하면 좋아!" 라는 글에 눈이 번쩍. 시행착오를 몇번 했지만 의외로 간단하더라. 1. VMWare건 VirtualBox건 상관없다. VM호스트를 준비하자. 2. http://www.android-x86.org/download 로 가서  Deprecated x86 2.2 generic  을 받자. Q) 왜 Deprecated 인 2.2 generic 을 받나요. Deprecated는 쓰면 안되는 거 아님? A) http://mariuz.android-dev.ro/vm.iso.7z 도 있다고 한다. http://www.android-x86.org/download 에 있는 요즘 것들은 죄다 안된다. 3. 죄다 일단 Default 설정에 yes yes 하고 설치한다. 한글 문서가 필요한 분은 ...