Created
March 25, 2022 18:39
-
-
Save S-codes14/ddbd1428682363938ef24e8d72f2e55b to your computer and use it in GitHub Desktop.
the source code for picsum photos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
interface PicsumConfig { | |
blur?: number; | |
cache?: boolean; | |
grayscale?: boolean; | |
height?: number; | |
id?: number; | |
jpg?: boolean; | |
width?: number; | |
} | |
interface QueryParams { | |
grayscale?: boolean; | |
blur?: number; | |
random?: number; | |
} | |
interface ImageObject { | |
id: number; | |
author: string; | |
width: number; | |
height: number; | |
url: string; | |
download_url: string; | |
} | |
const BASE_URL = 'https://picsum.photos' | |
const defaultConfig: PicsumConfig = { | |
blur: 0, | |
cache: true, | |
grayscale: false, | |
height: 200, | |
id: 0, | |
jpg: false, | |
width: 200, | |
} | |
const Picsum = { | |
/* | |
* Builds image URL | |
*/ | |
url (override: PicsumConfig = {}): string { | |
let url = BASE_URL | |
const config = { | |
...defaultConfig, | |
...override, | |
} | |
// Add different URL parts | |
if (config.id) { | |
url += `/id/${config.id}` | |
} | |
if (config.width) { | |
url += `/${config.width}` | |
} | |
if (config.height) { | |
url += `/${config.height}` | |
} | |
if (config.jpg) { | |
url += '.jpg' | |
} | |
// Add query params | |
const params: QueryParams = {} | |
if (config.grayscale) { | |
params.grayscale = config.grayscale | |
} | |
if (config.blur) { | |
params.blur = config.blur | |
} | |
if (config.cache) { | |
params.random = Math.floor(Math.random() * 10000) | |
} | |
const paramString = (Object.keys(params) as Array<keyof typeof params>).map(key => key + '=' + params[key]).join('&') | |
if (paramString) { | |
url += `?${paramString}` | |
} | |
return url | |
}, | |
/** | |
* Loads random image in full size | |
*/ | |
async random (): Promise<ImageObject> { | |
const page = Math.floor(Math.random() * 990) | |
const { data } = await axios.get(`https://picsum.photos/v2/list?page=${page}&limit=1`) | |
data[0].download_url += '.jpg' | |
return data[0] | |
}, | |
} | |
export { Picsum, defaultConfig } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment