Day07: GraphQL - with docker MongoDB


無敵大遲交XDD

接續 Day04Day05Day06 繼續玩下去:)

事前安裝

  • 跟 MongoDB 相關

    • npm install --save mongoose
  • 跟 建構假資料和其他 相關

    • npm install --save casual loadsh sequelize sqlite3
  • package.json 長這樣

    {
    "name": "graphql-node",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "nodemon ./index.js --exec babel-node -e js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
      "casual": "^1.6.2",
      "express": "^4.17.1",
      "express-graphql": "^0.9.0",
      "graphql": "^14.6.0",
      "graphql-tools": "^4.0.7",
      "lodash": "^4.17.15",
      "mongoose": "^5.9.2",
      "nodemon": "^2.0.2",
      "sequelize": "^5.21.5",
      "sqlite3": "^4.1.1"
    },
    "devDependencies": {
      "babel-cli": "^6.26.0",
      "babel-preset-env": "^1.7.0",
      "babel-preset-stage-0": "^6.24.1"
    }
    }
    
  • 安裝 Robo 3T MongoDB GUI

用 docker 跑一個 MongoDB

  • 原本教學影片是直接把 MongoDB 安裝到本機,想說都學 docker 了就直接來吧!
    • docker container run -d --name graphql-db2 -p 127.0.0.1:27017:27017 mongo
    • DockerHub: mongo
    • 不用設定 MONGO_INITDB_ROOT_USERNAMEMONGO_INITDB_ROOT_PASSWORD 本教學用的話會爆炸XDD 我卡一陣子

開一個資料夾把 resolvers.jsschema.js 丟進去,在這資料夾新建一個 dbConnections.js

  • 現在結構長這樣
    img

resolvers.jsschema.jsdbConnections.jsindex.js 的 code !

  • resolvers.js

    import mongoose from 'mongoose';
    import { Friends } from './dbConnectors';
    // resolver map
    export const resolvers = {
      Query: {
          getFriend: ({ id }) => {
              return new Friend(id, friendDatabase[id]);
          },
      },
      Mutation: {
          createFriend: (root,  {input}) => {
              const newFriend = new Friends({
                  firstName: input.firstName,
                  lastName: input.lastName,
                  gender: input.gender,
                  age: input.age,
                  language: input.language,
                  email: input.email,
                  contacts: input.contacts,
              });
              newFriend.id = newFriend._id;
              return new Promise((resolve, object) => {
                  newFriend.save((err)=>{
                      if (err) reject(err)
                      else resolve(newFriend)
                  })
              })
          },
      },
    };
    
  • schema.js

    import { resolvers } from './resolvers';
    import { makeExecutableSchema } from 'graphql-tools'
    const typeDefs = `
        type Friend{
            id: ID
            firstName: String
            lastName: String
            gender: Gender
            age: Int
            language: String
            email: String
            contacts: [Contact]
        }
    
        type Alien{
            id: ID
            firstName: String
            lastName: String
            planet: String
        }
    
        type Contact{
            firstName: String
            lastName: String
        }
    
        enum Gender{
            MALE
            FEMALE
            OTHER
        }
    
        type Query{
            getFriend(id: ID): Friend
        }
    
        input FriendInput{
          id: ID
          firstName: String!
          lastName: String
          gender: Gender
          age: Int
          language: String
          email: String
          contacts: [ContactInput]
        }
    
        input ContactInput{
          firstName: String
          lastName: String
        }
    
        type Mutation{
            createFriend(input: FriendInput): Friend
        }
    `;
    const schema = makeExecutableSchema( {typeDefs, resolvers} )
    export {schema};
    
  • dbConnections.js

    import mongoose from 'mongoose';
    import Sequelize from 'sequelize';
    import _ from 'lodash';
    import casual from 'casual';
    // Mongo Connection 
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost:27017/friends', {});
    const friendSchema = new mongoose.Schema({
      firstName:{
          type: String
      },
      lastName:{
          type: String
      },
      gender:{
          type: String
      },
      age:{
          type: Number
      },
      language:{
          type: String
      },
      email:{
          type: String
      },
      contacts:{
          type: Array
      },
    });
    const Friends = mongoose.model('friends', friendSchema);
    // SQL 
    const sequelize = new Sequelize('database', null, null, {
      dialect: 'sqlite',
      storage: './aliens.sqlite', // just like redis
    });
    const Aliens = sequelize.define('aliens', {
      firstName: { type: Sequelize.STRING },
      lastName: { type: Sequelize.STRING },
      planet: { type: Sequelize.STRING },
    });
    Aliens.sync({ force: true }).then(() => {
      _.times(10, (i)=> {
          Aliens.create({
              firstName: casual.first_name,
              lastName: casual.last_name,
              plane: casual.word,
          });
      });
    }); // create fake data
    export { Friends, Aliens };
    
  • index.js

    import express from 'express';
    import graphqlHTTP from 'express-graphql';
    import { schema } from './data/schema';
    const app = express();
    app.get('/', (req, res) => {
      res.send("GraphQL is amazing");
    });
    app.use("/graphql", graphqlHTTP({
      schema: schema,
      graphiql: true,
    }))
    app.listen(8080, () => console.log("Running server on port localhost:8080/graphql"));
    

Run 起來,然後塞資料,再去 Robo 3T 看資料

  • 看有沒有 error,記得 docker 要先 run 起來

  • 塞資料~
    img

  • 進 Robo 3T 看塞進去的資料
    • 塞成功啦!!!
      img

哈哈哈 Day07 最後一天 我遲交好多天!

  • 很有趣的平台,謝謝:)
  • 逼自己學一點點 YA!
  • 還有很多沒學、講完 ... 留到下次! XDDD
  • 當個時時督促自己的 procrastinator
  • 該把這邊的資料整理到我的部落格了 :) 
  • 好啦不完美的完美結束 ㄅㄅ~~

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








你可能感興趣的文章

Stripe Follow Along Dropdown

Stripe Follow Along Dropdown

[新手村系列] Markdown 和 HTML 基礎語法教學

[新手村系列] Markdown 和 HTML 基礎語法教學

金魚系列,排板篇

金魚系列,排板篇






留言討論