graphql-mesh mongoose 集成

内容来自官方的demo,主要是一个学习

环境准备

  • docker-compose
version: "3"
services: 
  mongodb:
    image: mongo:3
    ports:
    - "27017:27017"
  • 项目初始化
yarn  init -y
  • 添加依赖
yarn add @graphql-mesh/cli @graphql-mesh/mongoose @graphql-mesh/runtime graphql mongoose ts-node 
yarn add @types/mongoose @types/node typescript --dev
  • package.json
 {
  "name": "third",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@graphql-mesh/cli": "^0.0.16",
    "@graphql-mesh/mongoose": "^0.0.16",
    "@graphql-mesh/runtime": "^0.0.16",
    "graphql": "^14.6.0",
    "mongoose": "^5.9.6",
    "ts-node": "^8.8.1"
  },
  "scripts": {
    "start": "graphql-mesh serve"
  },
  "devDependencies": {
    "@types/mongoose": "^5.7.7",
    "@types/node": "^13.9.3",
    "typescript": "^3.8.3"
  }
}
  • 启动mongo 服务
docker-compose up -d 

集成使用

  • .meshrc.yml 文件
require:
  - ts-node/register/transpile-only
sources:
  - name: Mongoose
    handler:
      mongoose:
        connectionString: mongodb://localhost:27017/test
        models:
          - name: User
            path: ./src/models.ts#User
  • 模型定义
    src/models.ts
 
import { Schema, model } from 'mongoose';
const LanguagesSchema = new Schema(
  {
    language: String,
    skill: {
      type: String,
      enum: ['basic', 'fluent', 'native'],
    },
  },
  {
    _id: false, // disable `_id` field for `Language` schema
  }
);
const AddressSchema = new Schema({
  street: String,
  geo: {
    type: [Number], // [<longitude>, <latitude>]
    index: '2dsphere', // create the geospatial index
  },
});
export const UserSchema = new Schema(
  {
    name: {
      type: String,
      index: true,
    },
    age: {
      type: Number,
      index: true,
    },
    languages: {
      type: [LanguagesSchema], // you may include other schemas (also as array of embedded documents)
      default: [],
    },
    contacts: {
      // another mongoose way for providing embedded documents
      email: String,
      phones: [String], // array of strings
    },
    gender: {
      // enum field with values
      type: String,
      enum: ['male', 'female', 'ladyboy'],
    },
    address: {
      type: AddressSchema,
    },
    someMixed: {
      type: Schema.Types.Mixed,
      description: 'Some dynamic data',
    },
    salaryDecimal: {
      type: Schema.Types.Decimal128,
      index: true,
    },
  },
  {
    collection: 'user_users',
  }
);
UserSchema.index({ gender: 1, age: -1 });
export const User = model('User', UserSchema);
 
 
  • 启动服务
yarn start 
  • 效果

访问地址: http://localhost:4000

 

 

  • 数据操作

 

 

说明

基于graphql-mesh 强大handler 以及schema 转换能力,我们可以方便的进行graphql 数据的处理

参考资料

https://github.com/Urigo/graphql-mesh

posted on 2020-03-25 09:51  荣锋亮  阅读(303)  评论(0编辑  收藏  举报

导航