Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat various cleanup #65

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
bower_components
node_modules
/node_modules
/coverage
25 changes: 16 additions & 9 deletions graphql.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@
})
}

function __handleMethod(method, url, data, asJson) {
var cleaned = {url: url};
var isGet = method.toUpperCase() === 'GET';
if (asJson && !isGet) {
cleaned.body = JSON.stringify({query: data.query, variables: data.variables});
} else {
cleaned.url = url + '?' + "query=" + encodeURIComponent(data.query) + "&variables=" + encodeURIComponent(JSON.stringify(data.variables))
}
return cleaned;
}

var __doRequest

if (typeof XMLHttpRequest !== 'undefined') {
Expand Down Expand Up @@ -87,11 +98,8 @@
if (!url) {
return;
}
if (asJson) {
var body = JSON.stringify({query: data.query, variables: data.variables});
} else {
var body = "query=" + encodeURIComponent(data.query) + "&variables=" + encodeURIComponent(JSON.stringify(data.variables))
}
var cleaned = __handleMethod(method, url, data, asJson);

if (debug) {
console.groupCollapsed('[graphql]: '
+ method.toUpperCase() + ' ' + url + ': '
Expand All @@ -110,11 +118,11 @@

__doRequest(
method,
url,
cleaned.url,
asJson ? 'application/json' : 'application/x-www-form-urlencoded',
'application/json',
headers,
body,
cleaned.body,
onRequestError,
callback
)
Expand Down Expand Up @@ -191,8 +199,7 @@
* {a: {b: {c: 1, d: 2}}}, "a.b.c" => 1
*/
GraphQLClient.prototype.fragmentPath = function (fragments, path) {
var getter = new Function("fragments", "return fragments." + path.replace(/\./g, FRAGMENT_SEPERATOR))
var obj = getter(fragments)
var obj = fragments[path.replace(/\./g, FRAGMENT_SEPERATOR)]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this is changed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because it's equivalent, safer, and mentioned in #49

if (path != "on" && (!obj || typeof obj != "string")) {
throw new Error("Fragment " + path + " not found")
}
Expand Down
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
"url": "git+https://github.com/f/graphql-client.git"
},
"devDependencies": {
"babel-runtime": "^6.26.0",
"jest": "^27.4.5",
"jest-plugin-set": "^2.9.0",
"jest-mock-random": "^1.1.1",
"uglify-js": "^3.14.5"
},
Expand All @@ -36,5 +38,10 @@
"bugs": {
"url": "https://github.com/f/graphql-client/issues"
},
"homepage": "https://github.com/f/graphql-client#readme"
"homepage": "https://github.com/f/graphql-client#readme",
"jest": {
"setupFiles": [
"jest-plugin-set/setup"
]
}
}
68 changes: 44 additions & 24 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// to fake out graphql to use XHR so we can stub it
// to fake out graphql to use XHR, so we can stub it
global.XMLHttpRequest = null;

let {mockRandom} = require('jest-mock-random');
Expand Down Expand Up @@ -27,33 +27,33 @@ function mockXHR(status, data) {
return xhrMockObj;
}

/* global client, method, url, fetchPost, fetchComments */
describe('graphql.js', () => {
let client = null;

beforeEach(() => {
client = graphql(null, {
method: 'put',
set('url', () => null);
set('method', () => 'put');
set('client', () =>
graphql(url, {
method: method,
asJSON: true,
fragments: {
user: 'on User {name}',
auth: {
user: 'on User {token, ...user}'
}
}
});
client.fragment({
auth: {
error: 'on Error {messages}'
}
});
});
}));

it('client should be a function', () => {
expect(typeof client).toBe('function');
});

describe('.fragment()', () => {
it('registers a new fragment', () => {
client.fragment({
auth: {
error: 'on Error {messages}'
}
});

expect(client.fragment('auth.error')).toBe(
'fragment auth_error on Error {messages}'
Expand All @@ -77,7 +77,13 @@ describe('graphql.js', () => {
);
});

it('returns returns new fragments registered as well', () => {
it('returns new registered fragments as well', () => {
client.fragment({
auth: {
error: 'on Error {messages}'
}
});

expect(client.fragments()).toStrictEqual(
expect.objectContaining({
auth_error: '\nfragment auth_error on Error {messages}',
Expand All @@ -98,6 +104,12 @@ describe('graphql.js', () => {
}`;

it('mixes in the requested fragments and sets the data types', () => {
client.fragment({
auth: {
error: 'on Error {messages}'
}
});

var expectedQuery = `query ($name: String!, $bool: Boolean!, $int: Int!, $float: Float!, $id: ID!, $user_id: Int!, $postID: ID!, $custom_id: CustomType!, $customId: ID!, $target: [ID!]!) {
user(name: $name, bool: $bool, int: $int, id: $id) {
... auth_user
Expand Down Expand Up @@ -170,27 +182,35 @@ fragment auth_error on Error {messages}`;
});

describe('query testing', () => {
let fetchPost = null;
let fetchComments = null;

beforeEach(() => {
client.setUrl('https://example.org');
fetchPost = client.query(`{
set('fetchPost', () => client.query(`{
post(id: $id) {
id
title
text
}
}`);

fetchComments = client.query(`{
}`));
set('fetchComments', () => client.query(`{
commentsOfPost: comments(postId: $postId) {
comment
owner {
name
}
}
}`);
}`));

set('url', () => 'https://example.org');

describe('when method is GET', () => {
set('method', () => 'get');

it('makes the request passing the parameters as query arguments', () => {
let xhr = mockXHR(200, {});
xhr.send = jest.fn();
fetchPost({id: 123});
expect(xhr.send).toHaveBeenCalledWith(undefined);
expect(xhr.open).toHaveBeenCalledWith(method, expect.stringMatching(url), true)
expect(xhr.open).toHaveBeenCalledWith(method, expect.stringMatching(/\?query=.+&variables=/), true)
});
});

describe('when executing the queries normally', () => {
Expand Down
Loading