]> git.r.bdr.sh - rbdr/prompt/blame - src/lib/stores/prompt.js
Pass public path variable
[rbdr/prompt] / src / lib / stores / prompt.js
CommitLineData
38431710
RBR
1import { readable } from 'svelte/store';
2import { browser } from '$app/env';
3
4const internals = {
5f33c2b5 5 kVersion: '1:', // in case we need to force a re-fetch
0931cb4c
RBR
6 kHost: import.meta.env.VITE_PUBLIC_BASE_PATH || 'http://localhost:3000',
7 kDataPrefix: '/data/',
38431710
RBR
8 kAdjectivesPath: '/adjectives.json',
9 kNounsPath: '/nouns.json',
10
11 async get(locale, path) {
12
13 const shortLocale = locale.split('-')[0];
0931cb4c 14 const targetFile = internals.kHost + internals.kDataPrefix + shortLocale + path;
5f33c2b5 15 const data = browser && localStorage.getItem(internals.kVersion + targetFile);
38431710
RBR
16
17 if (data) {
18 return JSON.parse(data);
19 }
20
21 let newData = await (await fetch(targetFile)).json();
5f33c2b5 22 browser && localStorage.setItem(internals.kVersion + targetFile, JSON.stringify(newData));
38431710
RBR
23
24 return newData;
25 },
26
27 random(list) {
28
29 return list[Math.floor(Math.random() * list.length)];
30 }
31};
32
33export const getPrompt = function (locale) {
34
35 return readable(null, function (set) {
36
37 (async function() {
38
39 const adjectives = await internals.get(locale, internals.kAdjectivesPath);
40 const nouns = await internals.get(locale, internals.kNounsPath);
41
42 set(`${internals.random(nouns)}, ${internals.random(nouns)}, ${internals.random(adjectives)}`);
43 })();
44
45 return function stop() {};
46 });
47};