Skip to content

Instantly share code, notes, and snippets.

@jacques-blom
Created April 6, 2021 11:58
Show Gist options
  • Save jacques-blom/f8865daf289aad8977e72f7423664a2c to your computer and use it in GitHub Desktop.
Save jacques-blom/f8865daf289aad8977e72f7423664a2c to your computer and use it in GitHub Desktop.
Data Fetching in our Drawing Tool
import queryString, {ParsedUrlQueryInput} from 'querystring'
type RequestOptions = {
queryParams?: ParsedUrlQueryInput
method?: 'GET' | 'POST'
body?: object | string
}
export const apiUrl = (lambda: string, queryParams?: ParsedUrlQueryInput) => {
let url = `https://f10adraov8.execute-api.us-east-1.amazonaws.com/dev/${lambda}`
if (queryParams) url += '?' + queryString.stringify(queryParams)
return url
}
export const callApi = (lambda: string, options?: RequestOptions) => {
const {queryParams, body, method} = options || {}
const url = apiUrl(lambda, queryParams)
let bodyString = body
if (typeof bodyString === 'object') {
bodyString = JSON.stringify(body)
}
return fetch(url, {body: bodyString, method}).then((res) => res.json())
}
import {Box, Spinner} from '@chakra-ui/react'
import {getBorderColor} from '../../util'
export const RectangleLoading = ({selected}: {selected: boolean}) => {
return (
<Box
position="absolute"
border={`1px solid ${getBorderColor(selected)}`}
transition="0.1s border-color ease-in-out"
width="100%"
height="100%"
display="flex"
padding="2px"
>
<Box
flex="1"
border="3px dashed #101010"
borderRadius="255px 15px 225px 15px/15px 225px 15px 255px"
backgroundColor="white"
display="flex"
alignItems="center"
justifyContent="center"
>
<Spinner size="lg" thickness="3px" />
</Box>
</Box>
)
}
import {apiUrl} from './api'
export const getBorderColor = (visible: boolean) => {
return visible ? '#CCC' : 'transparent'
}
/**
* Returns the width and height for the specified image.
*/
export const getImageDimensions = (src: string) => {
return new Promise<{width: number; height: number}>((resolve, reject) => {
const image = new Image()
image.onload = () => {
resolve({width: image.width, height: image.height})
}
image.onerror = (error) => {
reject(error)
}
image.src = src
})
}
/**
* A function that returns a random image URL and that image's
* id, which can be used to refer back to that image in API requests.
*/
export const getRandomImage = () => {
const id = Date.now()
return {src: apiUrl('random-image', {seed: id}), id}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment