Day04: GraphQL Server setup with node.js


Initial GraphQL and Server setup

  • 事前作業:

1. npm init

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

2. npm install

  • npm install --save express nodemon graphql express-graphql
  • npm install --save-dev babel-cli babel-preset-env babel-preset-stage-0
  • 這時候資料夾應該長這樣

3.package.jsonscripts: 下加入客製的 start 指令

  • start":"nodemon ./index.js --exec babel-node -e js

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

  • 這時候資料夾應該長這樣
    • .babelrc 檔案 Object 參數設定

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

  • 這時候資料夾應該長這樣
  • 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

6. 在資料夾內新增 schema.js

  • 這時候資料夾應該長這樣
  • schema.js

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

7. 新增 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"));

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

Day04 作業

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

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








你可能感興趣的文章

一看就懂的 React 開發環境建置與 Webpack 入門教學

一看就懂的 React 開發環境建置與 Webpack 入門教學

Linux Mint 21.1 VNC Setup

Linux Mint 21.1 VNC Setup

ESM 模組 (ES6 Modules or JavaScript Modules)

ESM 模組 (ES6 Modules or JavaScript Modules)






留言討論