@
TommyLemon 从 graphql-js 摘取片段代码
github.com/graphql/graphql-js/blob/master/src/__tests__/starWarsSchema.js```js
const humanType = new GraphQLObjectType({
name: 'Human',
description: 'A humanoid creature in the Star Wars universe.',
fields: () => ({
id: {
type: GraphQLNonNull(GraphQLString),
description: 'The id of the human.',
},
name: {
type: GraphQLString,
description: 'The name of the human.',
},
friends: {
type: GraphQLList(characterInterface),
description:
'The friends of the human, or an empty list if they have none.',
resolve: human => getFriends(human),
},
appearsIn: {
type: GraphQLList(episodeEnum),
description: 'Which movies they appear in.',
},
homePlanet: {
type: GraphQLString,
description: 'The home planet of the human, or null if unknown.',
},
secretBackstory: {
type: GraphQLString,
description: 'Where are they from and how they came to be who they are.',
resolve() {
throw new Error('secretBackstory is secret.');
},
},
}),
interfaces: [characterInterface],
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
hero: {
type: characterInterface,
args: {
episode: {
description:
'If omitted, returns the hero of the whole saga. ' +
'If provided, returns the hero of that particular episode.',
type: episodeEnum,
},
},
resolve: (root, { episode }) => getHero(episode),
},
human: {
type: humanType,
args: {
id: {
description: 'id of the human',
type: GraphQLNonNull(GraphQLString),
},
},
resolve: (root, { id }) => getHuman(id),
},
droid: {
type: droidType,
args: {
id: {
description: 'id of the droid',
type: GraphQLNonNull(GraphQLString),
},
},
resolve: (root, { id }) => getDroid(id),
},
}),
});
```
从 dataloader 摘取片段代码
github.com/facebook/dataloader/blob/master/examples/SQL.md```js
var DataLoader = require('dataloader');
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('./to/your/db.sql');
// Dispatch a WHERE-IN query, ensuring response has rows in correct order.
var userLoader = new DataLoader(ids => {
var params = ids.map(id => '?' ).join();
var query = `SELECT * FROM users WHERE id IN (${params})`;
return queryLoader.load([query, ids]).then(
rows => ids.map(
id => rows.find(row =>
row.id === id) || new Error(`Row not found: ${id}`)
)
);
});
// Parallelize all queries, but do not cache.
var queryLoader = new DataLoader(queries => new Promise(resolve => {
var waitingOn = queries.length;
var results = [];
db.parallelize(() => {
queries.forEach((query, index) => {
db.all.apply(db, query.concat((error, result) => {
results[index] = error || result;
if (--waitingOn === 0) {
resolve(results);
}
}));
});
});
}), { cache: false });
// Usage
var promise1 = userLoader.load('1234');
var promise2 = userLoader.load('5678');
Promise.all([ promise1, promise2 ]).then(([ user1, user2]) => {
console.log(user1, user2);
});
```