npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

graphql-butler

v1.0.3

Published

Cliente GraphQL desenvolvido em NodeJS para facilitar o desenvolvimento de projetos JavaScript que usam GraphQL como API. A declaração de tipo TypeScript está dentro do pacote para projetos em TypeScript

Downloads

7

Readme

GraphQL Butler

Cliente GraphQL desenvolvido em NodeJS para facilitar o desenvolvimento de projetos JavaScript que usam GraphQL como API. A declaração de tipo TypeScript está dentro do pacote para projetos em TypeScript.

Instalação:


npm install graphql-butler

ou


yarn add graphql-butler

Introdução

Antes de começar a usar a ferramenta no seu projeto, veja quais são os principais métodos e qual sua função dentro do projeto:

| Método | Função | |---------------------|-----------------------------------------------------------| | Query | Responsável por realizar consultas de dados na API. | | Mutation | Envia requisições capazes criar, editar e excluir dados. | | Subscription | Consulta de dados real-time. |

Todas as requisições realizadas na ferramenta são obrigatóriamente do tipo POST para atender um dos requisitos básicos do GraphQL. Mas você não precisa se preocupar com métodos, requisição e resposta, pois a ferramenta cuidará de toda a parte burocrática para você.

Após adicionar o pacote ao seu projeto, você poderá usar métodos Query, Mutation e Subscription da seguinte maneira:

JavaScript:


const { Query, Mutation, Subscription } = require('graphql-butler');

TypeScript:


import { Query, Mutation, Subscription } from 'graphql-butler';

Endpoint

Você precisará instanciar uma variável obrigatória para deterinar qual será o endpoint (API) para onde serão enviadas as requisições GraphQL:


const api = "http://0.0.0.0:3000/graphql";

Headers (opcional)

Caso necessário, você também poderá instanciar os headers de sua preferência que será enviado dentro do corpo da requisição GraphQL, um exemplo:


const headers = {
	"Content-type": "application/json; charset=utf-8"
}

Modelo de consulta

Para cada método usado você não precisará instanciar o tipo de consulta dentro da sua requisição Query, Mutation ou Subscription, por exemplo:

Supondo que eu queira fazer uma consulta de um livro e quero que me retorne o nome do livro e o autor que seria da seguinte maneira:


query{
	book{
		title,
		author
	}
}

Usando o GraphQL Butler você não precisará incluir o tipo "query{...}" dentro do corpo da requisição, inclua apenas o que vem depois, isso também serve para os demais métodos. Vamos ver um exemplo prático de como deve ser usado:


const payload = `
	book(id: 1){
		title,
		author,
		status
	}
`

Documentação

Legal, agora é hora de colocar a mão no código e praticar.

Query

Examplo prático de consulta de livro usando o método Query:


import { Query } from "graphql-butler";
// const { Query } = require('graphql-butler');

const api = "http://0.0.0.0:3000/graphql";
const headers = {
	"Content-type": "application/json; charset=utf-8"
}

const GraphQL = new Query(api,headers);

const payload = `
	book{
		title,
		author,
	}
`

GraphQL.send(payload).then((data) => {
	console.log(data);
}).catch((err) => {
	console.log(err);
})

Em outro modelo, consultaremos dados passando uma id para identificar o livro na qual queremos buscar os dados:


import { Query } from "graphql-butler";
// const { Query } = require('graphql-butler');

const api = "http://0.0.0.0:3000/graphql";
const headers = {
	"Content-type": "application/json; charset=utf-8"
}

const GraphQL = new Query(api,headers);

const payload = `
	book(id: 1){
		title,
		author,
	}
`

GraphQL.send(payload).then((data) => {
	console.log(data);
}).catch((err) => {
	console.log(err);
})

Mutation

Agora vamos criar adicionar um livro enviando uma requisição que retornará o id do livro criado:


import { Mutation } from "graphql-butler";
// const { Mutation } = require('graphql-butler');

const api = "http://0.0.0.0:3000/graphql";
const headers = {
	"Content-type": "application/json; charset=utf-8"
}

const GraphQL = new Mutation(api,headers);

const payload = `
	book(
		title: "Teste",
		author: "Desconhecido"
	){
		id
	}
`

GraphQL.send(payload).then((data) => {
	console.log(data);
}).catch((err) => {
	console.log(err);
})

Subscription

Abrindo conexão real-time com subscription passando um id:


import { Subscription } from "graphql-butler";
// const { Subscription } = require('graphql-butler');

const api = "http://0.0.0.0:3000/graphql";
const headers = {
	"Content-type": "application/json; charset=utf-8"
}

const GraphQL = new Subscription(api,headers);

const payload = `
	book(
		title: "Teste",
		author: "Desconhecido"
	){
		id
	}
`

GraphQL.send(payload).then((data) => {
	console.log(data);
}).catch((err) => {
	console.log(err);
})

Licença

MIT License

Copyright (c) 2020 Daniel Pereira

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.