前端让接口提速的优化技巧

313 阅读1分钟

按需加载----graphQL

  • 背景:当后端返回的数据,给了太多不需要的字段时,graphQL会按需加载所需数据

  • 步骤:

    • 定义数据池root(里面就是所有数据)
    var root = {
    girls: [{
        id: 1,
        name: '女神一',
        iphone: 12345678910,
        weixin: 'xixixixi',
        height: 175,
        school: '剑桥大学',
        wheel: [{ name: '备胎1号', money: '24万元' }, { name: '备胎2号', money: '26万元' }]
    },
    {
        id: 2,
        name: '女神二',
        iphone: 12345678910,
        weixin: 'hahahahah',
        height: 168,
        school: '哈佛大学',
        wheel: [{ name: '备胎3号', money: '80万元' }, { name: '备胎4号', money: '200万元' }]
    }]
    }
    
    • 描述数据池中的数据结构schema
    const { buildSchema } = require('graphql');
    // 描述数据结构 schema
    var schema = buildSchema(`
    type Wheel {
        name: String,
        money: String
    }
    type Info {
        id: Int
        name: String
        iphone: Int
        weixin: String
        height: Int
        school: String
        wheel: [Wheel]
    }
    type Query {
        girls: [Info]
    }`);
    
    • 自定义查询数据query
    const { graphql } = require('graphql');
    
    // 定义查询内容
    const query = `
    { 
        girls {
            name
            wheel {
            	money
            }
        }
    }
    `;
    // 查询数据
    const result = await graphql(schema, query, root)