graphql#graphql JavaScript Examples

The following examples show how to use graphql#graphql. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: backend.test.js    From Spoke with MIT License 6 votes vote down vote up
// TODO: use test helper
async function createOrganization(user, name) {
  const context = getContext({ user });
  const orgQuery = `mutation createOrganization($name: String!) {
    createOrganization(name: $name) {
      id
      uuid
      name
      threeClickEnabled
      textingHoursEnforced
      textingHoursStart
      textingHoursEnd
    }
  }`;

  const variables = { name };

  try {
    return await graphql(mySchema, orgQuery, rootValue, context, variables);
  } catch (err) {
    console.error("Error creating organization");
    return false;
  }
}
Example #2
Source File: backend.test.js    From Spoke with MIT License 6 votes vote down vote up
it("should be undefined when user not logged in", async () => {
  const query = `{
    currentUser {
      id
    }
  }`;
  const context = getContext();
  const data = await graphql(mySchema, query, rootValue, context);

  expect(typeof data.currentUser).toEqual("undefined");
});
Example #3
Source File: backend.test.js    From Spoke with MIT License 6 votes vote down vote up
// TODO: refactor this whole test suite so it doesn't have to run sequentially
// TESTING CAMPAIGN CREATION FROM END TO END
it("should return the current user when user is logged in", async () => {
  testAdminUser = await createUser();
  const query = `{
    currentUser {
      email
    }
  }`;
  const context = getContext({ user: testAdminUser });
  const result = await graphql(mySchema, query, rootValue, context);
  const { data } = result;

  expect(data.currentUser.email).toBe(testAdminUser.email);
});
Example #4
Source File: backend.test.js    From Spoke with MIT License 6 votes vote down vote up
it("an admin can add texters to a organization by email", async () => {
  testTexterUser = await createUser({
    auth0_id: faker.random.uuid(),
    first_name: "TestTexterFirst",
    last_name: "TestTexterLast",
    cell: "555-555-6666",
    email: "[email protected]"
  });

  const addQuery = `
  mutation addUserToOrganizationByEmail($organizationId: String!, $email: String!, $role: String!) {
    addUserToOrganizationByEmail(organizationId: $organizationId, email: $email, role: $role)
  }`;
  const variables = {
    organizationId: testOrganization.data.createOrganization.id,
    email: testTexterUser.email,
    role: "TEXTER"
  };
  const context = getContext({ user: testAdminUser });
  const result = await graphql(
    mySchema,
    addQuery,
    rootValue,
    context,
    variables
  );

  expect(result.data.addUserToOrganizationByEmail).toBeTruthy();
});
Example #5
Source File: test_helpers.js    From Spoke with MIT License 6 votes vote down vote up
export async function createOrganization(user, name) {
  const context = getContext({ user });

  const orgQuery = `mutation createOrganization($name: String!) {
    createOrganization(name: $name) {
      id
      uuid
    }
  }`;

  const variables = { name: name || faker.company.companyName() };
  return await graphql(mySchema, orgQuery, rootValue, context, variables);
}
Example #6
Source File: test_helpers.js    From Spoke with MIT License 6 votes vote down vote up
export async function createTexter(organization, addedBy) {
  const user = await createUser({
    auth0_id: "test456",
    first_name: "TestTexterFirst",
    last_name: "TestTexterLast",
    cell: "555-555-6666",
    email: "[email protected]"
  });
  const addQuery = `
  mutation addUserToOrganizationByEmail($organizationId: String!, $email: String!, $role: String!) {
    addUserToOrganizationByEmail(organizationId: $organizationId, email: $email, role: $role)
  }`;
  const variables = {
    organizationId: organization.data.createOrganization.id,
    email: user.email,
    role: "TEXTER"
  };

  const context = getContext({ user: addedBy });
  await graphql(mySchema, addQuery, rootValue, context, variables);
  return user;
}
Example #7
Source File: test_helpers.js    From Spoke with MIT License 6 votes vote down vote up
export async function startCampaign(admin, campaign) {
  const startCampaignQuery = `mutation startCampaign($campaignId: String!) {
    startCampaign(id: $campaignId) {
      id
    }
  }`;
  const context = getContext({ user: admin });
  const variables = { campaignId: campaign.id };
  return await graphql(
    mySchema,
    startCampaignQuery,
    rootValue,
    context,
    variables
  );
}
Example #8
Source File: backend.test.js    From Spoke with MIT License 5 votes vote down vote up
async function createCampaign(user, title, description, organizationId) {
  const context = getContext({ user });

  const campaignInstance = new Campaign({
    organization_id: organizationId,
    creator_id: user.id
  });

  await campaignInstance.save();

  const campaignQuery = `mutation editCampaign($id: String!, $input: CampaignInput!) {
    editCampaign(id: $id, campaign: $input) {
      id
      title
    }
  }`;
  const variables = {
    id: campaignInstance.id,
    input: {
      title,
      description,
      organizationId
    }
  };

  try {
    const campaign = await graphql(
      mySchema,
      campaignQuery,
      rootValue,
      context,
      variables
    );

    if (campaign.errors) {
      console.error(campaign.errors);
    }
    console.log(campaign);

    return campaign;
  } catch (err) {
    console.error("Error creating campaign");
    return false;
  }
}
Example #9
Source File: test_helpers.js    From Spoke with MIT License 5 votes vote down vote up
export async function runGql(query, vars, user) {
  const context = getContext({ user });
  return await graphql(mySchema, query, rootValue, context, vars);
}
Example #10
Source File: test_helpers.js    From Spoke with MIT License 5 votes vote down vote up
export async function createCampaign(user, organization) {
  const title = "test campaign";
  const description = "test description";
  const organizationId = organization.data.createOrganization.id;
  const context = getContext({ user });

  const campaignInstance = new Campaign({
    organization_id: organizationId,
    creator_id: user.id,
    title,
    description,
    due_by: null,
    is_started: false,
    is_archived: false
  });

  await campaignInstance.save();

  const campaignQuery = `mutation editCampaign($id: String!, $input: CampaignInput!) {
    editCampaign(id: $id, campaign: $input) {
      id
    }
  }`;
  const variables = {
    id: campaignInstance.id,
    input: {
      title,
      description,
      organizationId
    }
  };
  const ret = await graphql(
    mySchema,
    campaignQuery,
    rootValue,
    context,
    variables
  );
  console.log(ret);
  return ret.data.editCampaign;
}
Example #11
Source File: test_helpers.js    From Spoke with MIT License 5 votes vote down vote up
export async function createScript(admin, campaign) {
  const campaignEditQuery = `
  mutation editCampaign($campaignId: String!, $campaign: CampaignInput!) {
    editCampaign(id: $campaignId, campaign: $campaign) {
      id
    }
  }`;
  const context = getContext({ user: admin });
  const campaignId = campaign.id;
  const variables = {
    campaignId,
    campaign: {
      interactionSteps: {
        id: "1",
        questionText: "Test",
        script: "{zip}",
        answerOption: "",
        answerActions: "",
        parentInteractionId: null,
        isDeleted: false,
        interactionSteps: [
          {
            id: "2",
            questionText: "hmm",
            script: "{lastName}",
            answerOption: "hmm",
            answerActions: "",
            parentInteractionId: "1",
            isDeleted: false,
            interactionSteps: []
          }
        ]
      }
    }
  };
  return await graphql(
    mySchema,
    campaignEditQuery,
    rootValue,
    context,
    variables
  );
}
Example #12
Source File: App.js    From Lambda with MIT License 5 votes vote down vote up
componentDidMount() {
    graphql(schema, '{ hello }').then(({ data }) => {
      this.setState({ result: data.hello });
    });
  }
Example #13
Source File: server.js    From OpenRichpedia with MIT License 5 votes vote down vote up
app.get('*', async (req, res, next) => {
  try {
    const css = new Set();

    // Enables critical path CSS rendering
    // https://github.com/kriasoft/isomorphic-style-loader
    const insertCss = (...styles) => {
      // eslint-disable-next-line no-underscore-dangle
      styles.forEach(style => css.add(style._getCss()));
    };

    // Universal HTTP client
    const fetch = createFetch(nodeFetch, {
      baseUrl: config.api.serverUrl,
      cookie: req.headers.cookie,
      schema,
      graphql,
    });

    // Global (context) variables that can be easily accessed from any React component
    // https://facebook.github.io/react/docs/context.html
    const context = {
      fetch,
      // The twins below are wild, be careful!
      pathname: req.path,
      query: req.query,
    };

    const route = await router.resolve(context);

    if (route.redirect) {
      res.redirect(route.status || 302, route.redirect);
      return;
    }

    const data = { ...route };
    data.children = ReactDOM.renderToString(
      <App context={context} insertCss={insertCss}>
        {route.component}
      </App>,
    );
    data.styles = [{ id: 'css', cssText: [...css].join('') }];

    const scripts = new Set();
    const addChunk = chunk => {
      if (chunks[chunk]) {
        chunks[chunk].forEach(asset => scripts.add(asset));
      } else if (__DEV__) {
        throw new Error(`Chunk with name '${chunk}' cannot be found`);
      }
    };
    addChunk('client');
    if (route.chunk) addChunk(route.chunk);
    if (route.chunks) route.chunks.forEach(addChunk);

    data.scripts = Array.from(scripts);
    data.app = {
      apiUrl: config.api.clientUrl,
    };

    const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
    res.status(route.status || 200);
    res.send(`<!doctype html>${html}`);
  } catch (err) {
    next(err);
  }
});
Example #14
Source File: 107-test.js    From cybsec with GNU Affero General Public License v3.0 4 votes vote down vote up
describe('github issue #107 merge Schema types on GQL', () => {
  it('get QueryTC from remote schema', () => {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    expect(RemoteQueryTC.getTypeName()).toBe('Query');
    expect(RemoteQueryTC.getFieldNames()).toEqual(['users']); // remoteMutationTC = ObjectTypeComposer.create(remoteSchema._mutationType);
    // remoteSubscriptionTC = ObjectTypeComposer.create(remoteSchema._subscriptionType);
  });
  it('get nested TC from remote schema', () => {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    const RemoteUserTC = RemoteQueryTC.get('users');
    expect(RemoteUserTC.getTypeName()).toEqual('User');
    const RemoteAccessTC = RemoteQueryTC.get('users.access');
    expect(RemoteAccessTC.getTypeName()).toEqual('Access');
  });
  it('schema stiching on Query',
  /*#__PURE__*/
  _asyncToGenerator(function* () {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    schemaComposer.Query.addFields(_objectSpread({
      tag: {
        type: schemaComposer.createObjectTC(`type Tag { id: Int, title: String}`),
        resolve: () => ({
          id: 1,
          title: 'Some tag'
        })
      }
    }, RemoteQueryTC.getFields()));
    expect(schemaComposer.Query.getFieldNames()).toEqual(['tag', 'users']);
    const schema = schemaComposer.buildSchema();
    expect((yield graphql(schema, `
          query {
            tag {
              id
              title
            }
            users {
              age
            }
          }
        `))).toEqual({
      data: {
        tag: {
          id: 1,
          title: 'Some tag'
        },
        users: [{
          age: 10
        }, {
          age: 20
        }, {
          age: 30
        }]
      }
    });
  }));
  it('schema stiching on Query.remote',
  /*#__PURE__*/
  _asyncToGenerator(function* () {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    schemaComposer.Query.addFields({
      tag: {
        type: schemaComposer.createObjectTC(`type Tag { id: Int, title: String}`),
        resolve: () => ({
          id: 1,
          title: 'Some tag'
        })
      },
      remote: {
        type: schemaComposer.createObjectTC({
          name: 'RemoteSchema',
          fields: RemoteQueryTC.getFields()
        }),
        resolve: () => ({}) // it's important to return something (not null/undefined)

      }
    });
    expect(schemaComposer.Query.getFieldNames()).toEqual(['tag', 'remote']);
    const schema = schemaComposer.buildSchema();
    expect((yield graphql(schema, `
          query {
            tag {
              id
              title
            }
            remote {
              users {
                age
              }
            }
          }
        `))).toEqual({
      data: {
        tag: {
          id: 1,
          title: 'Some tag'
        },
        remote: {
          users: [{
            age: 10
          }, {
            age: 20
          }, {
            age: 30
          }]
        }
      }
    });
  }));
  it('using remote type in local schema',
  /*#__PURE__*/
  _asyncToGenerator(function* () {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    const RemoteUserTC = RemoteQueryTC.getFieldTC('users');
    const remoteUsersFC = RemoteQueryTC.getFieldConfig('users');
    const LocalArticleTC = schemaComposer.createObjectTC({
      name: 'Article',
      fields: {
        text: {
          type: 'String'
        },
        author: {
          type: RemoteUserTC,
          args: _objectSpread({}, remoteUsersFC.args),
          resolve: (source, args, context, info) => {
            if (!remoteUsersFC.resolve) return null;
            const users = remoteUsersFC.resolve(source, args, context, info); // for simplicity return first user

            return users[0];
          }
        }
      }
    });
    schemaComposer.Query.addFields({
      article: {
        type: LocalArticleTC,
        resolve: () => ({
          text: 'Article 1'
        })
      }
    });
    const schema = schemaComposer.buildSchema();
    expect((yield graphql(schema, `
          query {
            article {
              text
              author {
                name
                age
                access {
                  msg
                }
              }
            }
          }
        `))).toEqual({
      data: {
        article: {
          text: 'Article 1',
          author: {
            access: {
              msg: 'disallowed'
            },
            age: 10,
            name: 'u1'
          }
        }
      }
    });
  }));
  it('adding remote type to SchemaComposer and check reference by name', () => {
    const RemoteQueryType = remoteSchema._queryType;
    const RemoteQueryTC = schemaComposer.createObjectTC(RemoteQueryType);
    const UserTC = RemoteQueryTC.getFieldTC('users');
    schemaComposer.add(UserTC);
    const ArticleTC = schemaComposer.createObjectTC({
      name: 'Article',
      fields: {
        user: 'User',
        users: ['User']
      }
    });
    const userType = ArticleTC.getFieldType('user');
    expect(userType).toBeInstanceOf(GraphQLObjectType);
    expect(userType.name).toBe('User');
    const usersType = ArticleTC.getFieldType('users');
    expect(usersType).toBeInstanceOf(GraphQLList);
    expect(usersType.ofType.name).toBe('User');
  });
});
Example #15
Source File: server.js    From OpenRichpedia with MIT License 4 votes vote down vote up
// app.use(
//   '/api/VisualLink',
//   createProxyMiddleware({
//     target: 'http://127.0.0.1:5001/',
//     changeOrigin: true,
//     pathRewrite: { '^/api': '/' },
//   }),
// );
// app.use(
//   '/api/dealImage',
//   createProxyMiddleware({
//     target: 'http://127.0.0.1:5001/',
//     changeOrigin: true,
//     pathRewrite: { '^/api': '/' },
//   }),
// );
app.get('*', async (req, res, next) => {
  try {
    const css = new Set();

    // Enables critical path CSS rendering
    // https://github.com/kriasoft/isomorphic-style-loader
    const insertCss = (...styles) => {
      // eslint-disable-next-line no-underscore-dangle
      styles.forEach(style => css.add(style._getCss()));
    };

    // Universal HTTP client
    const fetch = createFetch(nodeFetch, {
      baseUrl: config.api.serverUrl,
      cookie: req.headers.cookie,
      schema,
      graphql,
    });

    // Global (context) variables that can be easily accessed from any React component
    // https://facebook.github.io/react/docs/context.html
    const context = {
      fetch,
      // The twins below are wild, be careful!
      pathname: req.path,
      query: req.query,
    };

    const route = await router.resolve(context);

    if (route.redirect) {
      res.redirect(route.status || 302, route.redirect);
      return;
    }

    const data = { ...route };
    data.children = ReactDOM.renderToString(
      <App context={context} insertCss={insertCss}>
        {route.component}
      </App>,
    );
    data.styles = [{ id: 'css', cssText: [...css].join('') }];

    const scripts = new Set();
    const addChunk = chunk => {
      if (chunks[chunk]) {
        chunks[chunk].forEach(asset => scripts.add(asset));
      } else if (__DEV__) {
        throw new Error(`Chunk with name '${chunk}' cannot be found`);
      }
    };
    addChunk('client');
    if (route.chunk) addChunk(route.chunk);
    if (route.chunks) route.chunks.forEach(addChunk);

    data.scripts = Array.from(scripts);
    data.app = {
      apiUrl: config.api.clientUrl,
    };

    const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
    res.status(route.status || 200);
    res.send(`<!doctype html>${html}`);
  } catch (err) {
    next(err);
  }
});