Day04: GraphQL Server setup with node.js


Day04: GraphQL Server setup with node.js

Initial GraphQL and Server setup

  • 事前作業:

<span>1.</span> npm init

  • 找一個舒服的資料夾 npm init

<span>2.</span> npm install

  • npm install --save express nodemon graphql express-graphql
  • npm install --save-dev babel-cli babel-preset-env babel-preset-stage-0
  • 這時候資料夾應該長這樣
    • <span><img src="https://static.coderbridge.com/img/yuting3656/ca9361ee5fce4d63897113f1dff61135.jpg" width="40%" style="margin: 0" ></span>

<span>3.</span> 在 package.jsonscripts: 下加入客製的 start 指令

  • start":"nodemon ./index.js --exec babel-node -e js
    • <span><img src="https://static.coderbridge.com/img/yuting3656/5ca91b9f6fa848c79575b8c5e9c1167f.jpg" style="margin: 0"></span>

<span>4.</span> 在資料夾內新增 .babelrc 檔案,加入 Object 參數設定 讓 server 可 跑 ES6 code

  • 這時候資料夾應該長這樣
    • <span><img src="https://static.coderbridge.com/img/yuting3656/d5a7e2cd308340ec950b985d62a1efb6.jpg" style="margin: 0"></span>
    • .babelrc 檔案 Object 參數設定
    • <span><img src="https://static.coderbridge.com/img/yuting3656/0aa20977fdf447a7bbb135ee36050042.jpg" style="margin: 0"></span>

<span>5.</span> 在資料夾內新增 index.js,把 express run 起來~~

  • 這時候資料夾應該長這樣
    • <span><img src="https://static.coderbridge.com/img/yuting3656/3ccd00214abd4cfc9014c7d194662c48.jpg" style="margin: 0"></span>
  • index.js

    import express from 'express';
    
    const app = express();
    
    app.get('/', (req, res) => {
        res.send("GraphQL is amazing");
    });
    
    app.listen(8080, ()=> console.log("Running server on port localhost:8080/graphql"));
    
  • 跑起來

    • npm start
      • <span><img src="https://static.coderbridge.com/img/yuting3656/d295d77a956a4f00a5b399192751f6c9.jpg" style="margin: 0"></span>

<span>6.</span> 在資料夾內新增 schema.js

  • 這時候資料夾應該長這樣
    • <span><img src="https://static.coderbridge.com/img/yuting3656/bb6a3e5771b8452291671c2c2364a231.jpg" style="margin: 0"></span>
  • schema.js

    • import { buildSchema } from 'graphql';
      
      const schema = buildSchems(`
          type Query{
              hello: string
          }
      `)
      
      export default schema;
      

<span>7.</span> 新增 index.js 內容

import express from 'express';
import graphqlHTTP from 'express-graphql';
import schema from './schema';

const app = express();

app.get('/', (req, res) => {
    res.send("GraphQL is amazing");
});

const root = { hello: () => "Hi, I'm Yuting"};

app.use("/graphql", graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
}))

app.listen(8080, ()=> console.log("Running server on port localhost:8080/graphql"));

<span>8.</span> 跑起來~ 去看你的 http://localhost:8080/graphql

Day04 作業

  • yo~~ 東西都架出來了,可以自由發揮拉~
    • 把剛剛 hello schema 用 graphiql 叫出來~~~ _簡單啦!

其實我也是跟著影片學 XD 
Linkedin Learning
七天~ 逼一下自己






我都不會 GraphQL
模仿是最好的學習,耶! 一直很想學會&實作 GraphQL。就靠這七天拉!!! 七天內,把學到的嘎成文字和筆記:) PS.主要跟著: https://www.linkedin.com/learning/paths/stay-ahead-in-graphql?u=43607124

留言討論