diff --git a/index.js b/index.js index 327e363..b43044f 100644 --- a/index.js +++ b/index.js @@ -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 ( diff --git a/package-lock.json b/package-lock.json index b37cd4f..930f6b6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index be5f67f..91c9e2a 100644 --- a/package.json +++ b/package.json @@ -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",