A
A
asd dsa2020-01-22 21:11:25
JavaScript
asd dsa, 2020-01-22 21:11:25

How to use the same object but with different properties in different components?

Hi, at the time of initialization of the application, I change the real apolloClientone to a fictitious one, so that instead of requests to the server, give fictitious data. Everything works correctly, but there was a problem, in some components there is the same variable metricthat is assigned different values, (you cannot change the name of the variable in the components), the question is how to use this variable for different components while maintaining the uniqueness of the properties?
An example of data that comes from the server in different requests, for different components:
for one component: {metric: {id: 1, something: "meow"}}
For another: {metric: {id: 2, entities: 50}}
And so, I cannot create two variables metricor combine data into one variable metricbecause the data in the components will not be correct.
The place where I give away my mockups

import {
    metric
} from "./mockedData"

export const mocks = {
    Query: () => ({
        metric // здесь отдаю фиктивные данные в подменный apolloClient 
    })
}

where I create a dummy apolloClient (just for the sake of completeness)
import ApolloClient from "apollo-client"
import {
    makeExecutableSchema,
    addMockFunctionsToSchema,
} from "graphql-tools"
import { graphql, print } from "graphql"
import { InMemoryCache } from "apollo-cache-inmemory"
import { ApolloLink, Observable } from "apollo-link"

// simulate loading
function delay(ms) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve()
        }, ms)
    })
}

function createLink(schema, mocks) {
    const delayMs = 1000
    return new ApolloLink(operation => new Observable((observer) => {
        const { query, operationName, variables } = operation
        delay(delayMs)
            .then(() => graphql(
                schema,
                print(query),
                {},
                {},
                variables,
                operationName
            ))
            .then(() => {
                // inject mocked data here
                observer.next({ data: mocks.Query() })
                observer.complete()
            })
            .catch(observer.error.bind(observer))
    }))
}

export function createMockedClient({
    typeDefs,
    mocks,
}) {
    const schema = makeExecutableSchema({ typeDefs })

    const mockOptions = {
        schema,
        mocks,
    }

    addMockFunctionsToSchema(mockOptions)

    const cache = new InMemoryCache()

    return new ApolloClient({
        cache,
        link: ApolloLink.from([
            createLink(schema, mocks),
        ]),
        connectToDevTools: true,
    })
}

Help please =^.^=

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Lanets, 2020-01-22
@Fi1osof

To complete the picture, it was also necessary to attach a diagram of your component.
If your schema is something like this:

type Metric {
  id: Int!
  something: String
}

and you want it to be able to correctly return entities: 50, then the most correct thing is to add this property to the model itself.
type Metric {
  id: Int!
  """ Боевая переменная """
  something: String

  """ Для тестов """
  entities: Int
}

That is, you have both variables in the schema, you can transfer any property, while the fields are not required, so if it is not received, then it's okay.
This is essentially the single most convenient way to do this.
If your situation is more complicated (there are much more fields in combat mode and you do not want to list all the fields), then for insignificant models you can set the JSON type at all.
If you are using Apollo-Server, here is their official instruction: https://www.apollographql.com/docs/graphql-tools/s...
Then your object can have any set of valid properties. But I do not advise you to get involved in this, it often leads to chaos.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question