Add filter to countries field

This commit is contained in:
Trevor Blades
2020-03-29 13:59:32 -07:00
parent c78571d130
commit 7e0d2de6ed
3 changed files with 51 additions and 7 deletions

View File

@@ -1,3 +1,4 @@
const sift = require('sift');
const provinces = require('provinces');
const {ApolloServer, gql} = require('apollo-server');
const {continents, countries, languages} = require('countries-list');
@@ -36,16 +37,51 @@ const typeDefs = gql`
rtl: Boolean!
}
input CountryFilterInput {
code: StringQueryOperatorInput
currency: StringQueryOperatorInput
continent: StringQueryOperatorInput
}
input StringQueryOperatorInput {
eq: String
ne: String
in: [String]
nin: [String]
regex: String
glob: String
}
type Query {
continents: [Continent!]!
continent(code: ID!): Continent
countries: [Country!]!
countries(filter: CountryFilterInput): [Country!]!
country(code: ID!): Country
languages: [Language!]!
language(code: ID!): Language
}
`;
function siftifyFilter(filter) {
return Object.entries(filter).reduce(
(acc, [key, operators]) => ({
...acc,
[key]: siftifyOperators(operators)
}),
{}
);
}
function siftifyOperators(operators) {
return Object.entries(operators).reduce(
(acc, [operator, value]) => ({
...acc,
['$' + operator]: value
}),
{}
);
}
const resolvers = {
Country: {
capital: country => country.capital || null,
@@ -105,11 +141,13 @@ const resolvers = {
}
);
},
countries: () =>
Object.entries(countries).map(([code, country]) => ({
...country,
code
})),
countries: (parent, {filter = {}}) =>
Object.entries(countries)
.map(([code, country]) => ({
...country,
code
}))
.filter(sift(siftifyFilter(filter))),
language(parent, {code}) {
const language = languages[code];
return (

5
package-lock.json generated
View File

@@ -4153,6 +4153,11 @@
}
}
},
"sift": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/sift/-/sift-12.0.0.tgz",
"integrity": "sha512-aWQoexMzacDdUrUuPWLrvfHiYCW7QyMYZ6D7ipkuas7gdvn0GoUVzU/fyvPpgPjS49IRvZktCQWYxgWOwACk/A=="
},
"signal-exit": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",

View File

@@ -11,7 +11,8 @@
"apollo-server": "^2.10.1",
"countries-list": "^2.5.4",
"graphql": "^14.6.0",
"provinces": "^1.11.0"
"provinces": "^1.11.0",
"sift": "^12.0.0"
},
"devDependencies": {
"@trevorblades/eslint-config": "^7.0.2",