diretto/src/store/actions.ts

43 lines
1.2 KiB
TypeScript

import { ActionTree } from "vuex";
import { AppState, EventFeed, FeedEvent } from "./types";
import { toEvent } from "./feed";
import Parser from "rss-parser";
import { mustArray } from "@/utils";
const actions: ActionTree<AppState, AppState> = {
// Add one or more sources
addSources({ commit, dispatch }, sources: EventFeed[]) {
// Commit to state immediately
commit("appendSources", sources);
// Start fetching from each new source
sources.forEach(x => dispatch("fetchFromSource", x.url));
},
// Fetch events from a source url
async fetchFromSource({ commit }, url: string) {
try {
const parser = new Parser();
const feed = await parser.parseURL(url);
// Parse events
const events: FeedEvent[] = mustArray(feed.items)
.map(toEvent)
.map(x => ({
source: url,
data: x
}));
commit("setSourceStatus", {
url,
info: { title: feed.title, description: feed.description },
status: { fetched: true, events }
});
} catch (e) {
commit("setSourceStatus", {
url,
status: { fetched: true, error: e }
});
}
}
};
export default actions;