sql >> Database >  >> RDS >> Mysql

GraphQL - retourneer berekend type afhankelijk van argument

Joe's antwoord (voeg {"name":"ratio" , value:data.active/data.total} toe naar het resultaat zodra het resultaat uit de database is opgehaald) zou dit doen zonder schemawijzigingen aan te brengen.

Als alternatieve methode of als een elegantere manier om het in GraphQL te doen, kunnen de veldnamen in het type zelf worden opgegeven in plaats van ze als argumenten door te geven. En bereken ratio door een resolver te schrijven.

Het GraphQL-schema zou dus zijn:

Item {
  total: Int,
  active: Int,
  ratio: Float
}

type Query {
  items: [Item]
}

De klant specificeert de velden:

{
  items {
    total 
    active 
    ratio
  }
}

En ratio kan worden berekend in de resolver.

Hier is de code:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { graphql } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const getFieldNames = require('graphql-list-fields');

const typeDefs = `
type Item {
  total: Int,
  active: Int,
  ratio: Float
}

type Query {
  items: [Item]
}
`;

const resolvers = {
  Query: {
    items(obj, args, context, info) {
      const fields = getFieldNames(info) // get the array of field names specified by the client
      return context.db.getItems(fields)
    }
  },
  Item: {
    ratio: (obj) => obj.active / obj.total // resolver for finding ratio
  }
};

const schema = makeExecutableSchema({ typeDefs, resolvers });

const db = {
  getItems: (fields) => // table.select(fields)
    [{total: 10, active: 5},{total: 5, active: 5},{total: 15, active: 5}] // dummy data
}
graphql(
  schema, 
  `query{
    items{
      total,
      active,
      ratio
    }
  }`, 
  {}, // rootValue
  { db } // context
).then(data => console.log(JSON.stringify(data)))


  1. De wizard Metagegevens zoeken gebruiken

  2. Een andere tabel bijwerken na het invoegen met behulp van een trigger?

  3. wat is deze volgorde van 1?

  4. Onjuiste tekenreekswaarde:'\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL