nonocast / issues

personal blog (outdate)
1 stars 0 forks source link

stack index #1

Open nonocast opened 6 years ago

nonocast commented 6 years ago

solution

frontend

backend (api only)

几个原因

koa

  1. startup

    mkdir demo
    yarn add koa koa-router --save
    yarn add nodemon --save-dev
  2. app.js

    
    const Koa = require('koa');
    const cors = require('koa2-cors')
    const Router = require('koa-router')

let app = new Koa(); let router = new Router();

router.get('/', async (ctx) => { ctx.body = "hello world"; });

router.get('/ctx', async (ctx) => { ctx.body = ctx; })

let server = app .use(cors()) .use(router.routes()) .use(router.allowedMethods()) .listen(9000); console.log(server is starting at port ${server.address().port});


3. package.json

"scripts": { "start": "nodemon --delay 2 app.js" },


4. yarn start

# react

1. npx create-react-app webapp
2. yarn add antd react-router react-router-dom lodash --save
3. yarn start

# MongoDB

1. [mlab](https://mlab.com) (500m免费mongodb福利)
2. 创建db, collection和user, 获取mongodb://<dbuser>:<dbpassword>@ds243325.mlab.com:43325/m365
3. 通过`mongo ds243325.mlab.com:43325/m365 -u <dbuser> -p <dbpassword>`交叉验证服务可用性,$ show collections & $ show {collections}.find()
4. 创建一些测试的documents,id会自动生成

# mongoose

const mongoose = require('mongoose') mongoose.connect('mongodb://user:pwd@ds243325.mlab.com:43325/m365', {useNewUrlParser: true}); const Meeting = mongoose.model('meetings', {name: String});

router.get('/', async (ctx) => { ctx.body = await Meeting.find({}); });


# GraphQL Server for Koa
`yarn add apollo-server-koa graphql --save `

const { ApolloServer, gql } = require('apollo-server-koa');

const typeDefs = gql type Query { hello: String } ;

const resolvers = { Query: { hello: () => 'Hello world!', }, };

let app = new Koa(); const apollo = new ApolloServer({ typeDefs, resolvers }); apollo.applyMiddleware({ app }); ... console.log(apollo: ${apollo.graphqlPath});


open http://localhost:9000/graphql
![screen shot 2018-10-24 at 7 24 22 pm](https://user-images.githubusercontent.com/1457904/47427340-9e0bc980-d7c2-11e8-9bd2-d554c24bdd78.jpg)

你可以通过{ hello }查询,服务根据query然后通过resolvers进行解析。

# GraphQL client for React
`yarn add apollo-boost react-apollo graphql --save`

import ApolloClient from "apollo-boost"; import gql from "graphql-tag";

const client = new ApolloClient({ uri: "http://localhost:9000/graphql" });

componentDidMount() { client.query({ query: gql{ hello } }).then(result => { this.setState({ hello: result.data.hello }) }); }


然后就是翻成react way,穿衣服,注入context
index.js

import { ApolloProvider } from "react-apollo"; import ApolloClient from "apollo-boost";

const client = new ApolloClient({ uri: "http://localhost:9000/graphql" });

let app = (

);


app.js
{({ loading, error, data }) => { return

{data.hello}

}}
nonocast commented 6 years ago

GraphQL Server

Query和Resolver名字约定一致。