6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【now】ApolloServerを無料でサーバにデプロイする

Last updated at Posted at 2020-03-19

概要

  • ApolloServerで作ったGraphQLサーバをどこかにデプロイしたい!と思って調べた手順です
  • nowを使えば実現することができました

サンプル用ApolloServer作成

  • デプロイするための最小のApolloServerを作ります
mkdir apollo-server-sample
cd apollo-server-sample
yarn init -y
yarn add apollo-server graphql
  • index.jsを作成します
    • 公式のサンプルを拝借
index.js
const { ApolloServer, gql } = require('apollo-server');

const books = [
  { title: 'Harry Potter and the Chamber of Secrets', author: 'J.K. Rowling' },
  { title: 'Jurassic Park', author: 'Michael Crichton' },
];

const typeDefs = gql`
  type Query {
    books: [Book]
  }
  type Book {
    title: String
    author: String
  }
`;

const resolvers = {
  Query: {
    books: () => books,
  },
};

const server = new ApolloServer({ typeDefs, resolvers, cors: true });

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});
  • package.jsonのscriptsに起動コマンドを追加します
package.json
{
  "name": "apollo-server-sample",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "apollo-server": "^2.11.0",
    "graphql": "^14.6.0"
  },
  "scripts": {
    "start": "node index.js"
  }
}

nowのセッティング

  • now.jsonを作成します
now.json
{
  "version": 2,
  "builds": [{ "src": "index.js", "use": "@now/node" }],
  "routes": [{ "src": ".*", "dest": "index.js" }]
}
  • nowのcliをインストール
# 執筆時点ではバグがあるため@canaryで最新版をインストールしている
npm i -g now@canary
  • nowにログイン
now login
  • メールアドレスを入力しメールが来るのでVerifyする

デプロイ

dev環境へのデプロイ

  • Playgroundが動いてほしいのでNODE_ENVにdevelopmentを指定
now -e NODE_ENV=development
  • いろいろきかれますがエンター連打でOK
  • 完了するとURLが表示されます
    • アクセスしてPlaygroundが表示されればOK
    • clientから叩いてもちゃんと動作するはずです

prod環境へデプロイ

now --prod
  • こちらも完了するとURLが表示されます
    • prodなのでPlaygroundは表示されません
    • clientから叩けばちゃんと動作するはずです

まとめ

  • now便利だけどサーバもデプロイできるとは知らなかった!
  • 簡単にデプロイできて便利!

おまけ

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?