Skip to content

Commit

Permalink
feat(currency): return either string or float value
Browse files Browse the repository at this point in the history
  • Loading branch information
thuoe committed Mar 25, 2024
1 parent 58bee40 commit 10f0e25
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
7 changes: 4 additions & 3 deletions src/directives/currency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,17 @@ const currencyDirective = (directiveName: string = 'currency') => {
validateCodes(from, to)
const { fieldName, returnType } = info
const type = returnType.toString()
if (type !== 'String') {
throw new GraphQLError(`Unable to validate field "${fieldName}" of type ${type}. @currency directive can only be used on scalar type String`)
if (type !== 'String' && type !== 'Float') {
throw new GraphQLError(`Unable to validate field "${fieldName}" of type ${type}. @currency directive can only be used on scalar type String or Float`)
}
const value = await resolve(source, args, context, info)
try {
const response = await fetch(`https://www.google.com/search?q=${value}+${from}+to+${to}+&hl=en`)
const html = await response.text()
const $ = cheerio.load(html)
const $input = $('.iBp4i') // TODO: hacky... find better selector
return $input.text().split(' ')[0]
const amount = $input.text().split(' ')[0]
return type === 'String' ? amount : type === 'Float' ? Number(amount) : null
} catch (error) {
throw new GraphQLError(`Error converting amount ${value} from ${from} to ${to}!`, error)
}
Expand Down
8 changes: 3 additions & 5 deletions test/currency.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ApolloServer } from '@apollo/server'
import assert from 'assert'
import currencyDirective from '@src/directives/currency'
import { ApolloServer } from '@apollo/server'
import { buildSchema } from './util'
import assert from 'assert'


const { currencyDirectiveTypeDefs, currencyDirectiveTransformer } = currencyDirective()

Expand Down Expand Up @@ -64,9 +65,6 @@ describe('@currency directive', () => {
expect(fetchSpy).toHaveBeenCalledWith(`https://www.google.com/search?q=${amount}+${from}+to+${to}+&hl=en`)
})

it.todo('will convert from one currency to another and return a integer')
it.todo('will convert from one currency to another and format with a seperator')

it('will throw an error if currency code(s) are not recognized', async () => {
const fetchSpy = jest.spyOn(global, 'fetch')
const from = 'BLAH'
Expand Down

0 comments on commit 10f0e25

Please sign in to comment.