This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
SWAPI, Paging, DataLoader, Request ID #242
Open
alexbaluhin
wants to merge
16
commits into
ctco:master
Choose a base branch
from
alexbaluhin:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
171cdfc
Update dependencies (except apollo-server-koa)
alexbaluhin fb5c8c9
Merge branch 'master' of https://github.com/ctco/nodejs-graphql-template
alexbaluhin 5375e3d
GraphQlGen
alexbaluhin 6c54662
Merge branch 'master' of https://github.com/ctco/nodejs-graphql-template
alexbaluhin d3c8a0b
Move all paths to paths.ts
alexbaluhin 5200db1
GraphQL schema derive out of multiple files
alexbaluhin 2e96c9c
Merge branch 'master' of https://github.com/ctco/nodejs-graphql-template
alexbaluhin 5a266de
Merge branch 'master' of https://github.com/ctco/nodejs-graphql-template
alexbaluhin da863e5
Update jest CI config
alexbaluhin 6303b2f
Merge branch 'master' of https://github.com/ctco/nodejs-graphql-template
alexbaluhin cc73c50
SWAPI, Paging, DataLoader
alexbaluhin e2b5551
Lint, README.md update
alexbaluhin 0948466
Integration test for SWAPI
alexbaluhin 4f2ea13
Fix, update comments
alexbaluhin e17c60d
Remove redundant and useless comments
alexbaluhin 972f32a
Request ID logging
alexbaluhin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import DataLoader from 'dataloader'; | ||
import { createClient } from 'flashheart'; | ||
import logger from '../logger'; | ||
|
||
const http = createClient({ logger, timeout: 5000 }); | ||
|
||
async function getFromUrl(url) { | ||
const response = await http.getAsync(url); | ||
return response; | ||
} | ||
|
||
export const dataLoader = new DataLoader(urls => | ||
Promise.all(urls.map(getFromUrl)), | ||
); | ||
|
||
export const getObjectFromUrl = async (url: string): Promise<any> => dataLoader.load(url); | ||
|
||
export const getObjectsFromType = async (type: string): Promise<any> => { | ||
return await getObjectFromUrl(`${process.env.SWAPI_SERVICE_URL}/${type}/`); | ||
}; | ||
|
||
export const getObjectFromTypeAndId = async (type: string, id: string): Promise<any> => { | ||
const data = await getObjectFromUrl(`${process.env.SWAPI_SERVICE_URL}/${type}/${id}/`); | ||
return objectWithId(data); | ||
}; | ||
|
||
export const getObjectsFromUrls = async (urls: string[]): Promise<any[]> => { | ||
const array = await Promise.all(urls.map(getObjectFromUrl)); | ||
return array.map(objectWithId); | ||
}; | ||
|
||
/** | ||
* Objects returned from SWAPI don't have an ID field, so add one. | ||
*/ | ||
export const objectWithId = (obj: {id: number, url: string}): Object => { | ||
obj.id = parseInt(obj.url.split('/')[5], 10); | ||
return obj; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
/** | ||
* Type definitions for third party libraries. | ||
*/ | ||
interface Storage extends Map<any, any> { | ||
enter: Function; | ||
exit: Function; | ||
} | ||
|
||
/** | ||
* Merging default type definitions with below. | ||
*/ | ||
declare module NodeJS { | ||
interface Process { | ||
storage: Storage; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// Jest Snapshot v1, https://goo.gl/fbAQLP | ||
|
||
exports[`query.swapi should match snapshot with pagination 1`] = ` | ||
Object { | ||
"data": Object { | ||
"allFilms": Object { | ||
"edges": Array [ | ||
Object { | ||
"cursor": "YXJyYXljb25uZWN0aW9uOjA=", | ||
"node": Object { | ||
"episodeID": 4, | ||
"title": "A New Hope", | ||
}, | ||
}, | ||
Object { | ||
"cursor": "YXJyYXljb25uZWN0aW9uOjE=", | ||
"node": Object { | ||
"episodeID": 2, | ||
"title": "Attack of the Clones", | ||
}, | ||
}, | ||
], | ||
"films": Array [ | ||
Object { | ||
"episodeID": 4, | ||
"title": "A New Hope", | ||
}, | ||
Object { | ||
"episodeID": 2, | ||
"title": "Attack of the Clones", | ||
}, | ||
], | ||
"pageInfo": Object { | ||
"endCursor": "YXJyYXljb25uZWN0aW9uOjE=", | ||
"hasNextPage": false, | ||
"hasPreviousPage": false, | ||
"startCursor": "YXJyYXljb25uZWN0aW9uOjA=", | ||
}, | ||
"totalCount": 2, | ||
}, | ||
}, | ||
"errors": undefined, | ||
} | ||
`; | ||
|
||
exports[`query.swapi should match snapshot without pagination 1`] = ` | ||
Object { | ||
"data": Object { | ||
"film": Object { | ||
"episodeID": 5, | ||
"title": "The Empire Strikes Back", | ||
}, | ||
}, | ||
"errors": undefined, | ||
} | ||
`; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
import { graphql } from 'graphql'; | ||
import schema from '../schema'; | ||
import nock from 'nock'; | ||
|
||
const rootValue = {}; | ||
const context = {}; | ||
|
||
beforeAll(() => { | ||
|
||
// mock service endpoint | ||
|
||
const filmsResponse = { | ||
count: 2, | ||
next: null, | ||
previous: null, | ||
results: [ | ||
{ | ||
title: 'A New Hope', | ||
episode_id: 4, | ||
url: 'https://swapi.co/api/films/', | ||
}, | ||
{ | ||
title: 'Attack of the Clones', | ||
episode_id: 2, | ||
url: 'https://swapi.co/api/films/', | ||
}, | ||
], | ||
}; | ||
|
||
nock(process.env.SWAPI_SERVICE_URL!) | ||
.get('/films/') | ||
.reply(200, filmsResponse); | ||
|
||
const filmResponse = { | ||
title: 'The Empire Strikes Back', | ||
episode_id: 5, | ||
url: 'https://swapi.co/api/films/2/', | ||
}; | ||
|
||
nock(process.env.SWAPI_SERVICE_URL!) | ||
.get('/films/2/') | ||
.reply(200, filmResponse); | ||
}); | ||
|
||
describe('query.swapi', () => { | ||
it('should match snapshot with pagination', async () => { | ||
const query = ` | ||
query Q { | ||
allFilms { | ||
edges { | ||
node { | ||
title | ||
episodeID | ||
} | ||
cursor | ||
} | ||
pageInfo { | ||
startCursor | ||
endCursor | ||
hasNextPage | ||
hasPreviousPage | ||
} | ||
totalCount | ||
films { | ||
title | ||
episodeID | ||
} | ||
} | ||
} | ||
`; | ||
|
||
const result = await graphql(schema, query, rootValue, context); | ||
const { data, errors } = result; | ||
|
||
expect({ data, errors }).toMatchSnapshot(); | ||
}); | ||
|
||
it('should match snapshot without pagination', async () => { | ||
const query = ` | ||
query Q { | ||
film(filmID: 2) { | ||
title | ||
episodeID | ||
} | ||
} | ||
`; | ||
|
||
const result = await graphql(schema, query, rootValue, context); | ||
const { data, errors } = result; | ||
|
||
expect({ data, errors }).toMatchSnapshot(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import { connectionDefinitions } from 'graphql-relay-tools'; | ||
|
||
/** | ||
* Constructs a GraphQL connection field config; it is assumed | ||
* that the object has a property named `prop`, and that property | ||
* contains a list of types. | ||
*/ | ||
export function connectTypes(name: string, prop: string, type: string) { | ||
const { connectionType } = connectionDefinitions({ | ||
name, | ||
nodeType: type, | ||
connectionFields: ` | ||
totalCount: Int | ||
${prop}: [${type}] | ||
`, | ||
}); | ||
|
||
return connectionType; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import * as swapi from '../../connectors/swapi'; | ||
|
||
type ObjectsByType = { | ||
objects: Object[], | ||
totalCount: number, | ||
}; | ||
|
||
/** | ||
* Given a type, fetch all of the pages, and join the objects together | ||
*/ | ||
const byType = async (type: string): Promise<ObjectsByType> => { | ||
const typeData = await swapi.getObjectsFromType(type); | ||
let objects: Object[] = []; | ||
let nextUrl = typeData.next; | ||
|
||
objects = objects.concat(typeData.results.map(swapi.objectWithId)); | ||
while (nextUrl) { | ||
const pageData = await swapi.getObjectFromUrl(nextUrl); | ||
objects = objects.concat(pageData.results.map(swapi.objectWithId)); | ||
nextUrl = pageData.next; | ||
} | ||
|
||
objects = sortObjectsById(objects); | ||
return { objects, totalCount: objects.length }; | ||
}; | ||
|
||
const byTypeAndId = async (type: string, id: string): Promise<Object> => swapi.getObjectFromTypeAndId(type, id); | ||
|
||
const byUrl = async (url: string): Promise<any> => { | ||
const data = await swapi.getObjectFromUrl(url); | ||
return swapi.objectWithId(data); | ||
}; | ||
|
||
const byUrls = async (urls: string[]): Promise<any[]> => { | ||
const array = await swapi.getObjectsFromUrls(urls); | ||
return sortObjectsById(array); | ||
}; | ||
|
||
const sortObjectsById = (array: any[]): Object[] => { | ||
return array.sort((a, b) => a.id - b.id); | ||
}; | ||
|
||
const convertToNumber = (value: string): number | null => { | ||
if (['unknown', 'n/a'].indexOf(value) !== -1) { | ||
return null; | ||
} | ||
|
||
// remove digit grouping | ||
const numberString = value.replace(/,/, ''); | ||
return Number(numberString); | ||
}; | ||
|
||
export { | ||
byTypeAndId, | ||
byType, | ||
byUrl, | ||
byUrls, | ||
convertToNumber, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export const node = { | ||
__resolveType: () => null, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why not spread over
resolvers
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Generated TypeScript interface
Resolvers
does not contain SWAPI resolvers types.