]> git.r.bdr.sh - rbdr/prompt/blob - src/lib/stores/prompt.js
Pass public path variable
[rbdr/prompt] / src / lib / stores / prompt.js
1 import { readable } from 'svelte/store';
2 import { browser } from '$app/env';
3
4 const internals = {
5 kVersion: '1:', // in case we need to force a re-fetch
6 kHost: import.meta.env.VITE_PUBLIC_BASE_PATH || 'http://localhost:3000',
7 kDataPrefix: '/data/',
8 kAdjectivesPath: '/adjectives.json',
9 kNounsPath: '/nouns.json',
10
11 async get(locale, path) {
12
13 const shortLocale = locale.split('-')[0];
14 const targetFile = internals.kHost + internals.kDataPrefix + shortLocale + path;
15 const data = browser && localStorage.getItem(internals.kVersion + targetFile);
16
17 if (data) {
18 return JSON.parse(data);
19 }
20
21 let newData = await (await fetch(targetFile)).json();
22 browser && localStorage.setItem(internals.kVersion + targetFile, JSON.stringify(newData));
23
24 return newData;
25 },
26
27 random(list) {
28
29 return list[Math.floor(Math.random() * list.length)];
30 }
31 };
32
33 export 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 };