Give the job tracker stores and fix the admin route guard

createCrudStore captures the places store's pattern and now backs
places, job applications and job references. JobApplications.vue no
longer calls gql() itself and is split into the applications table, the
references table and the add form, with the status vocabulary in
jobStatus.js.

api.js is a thin REST client that turns failures into an ApiError
carrying the backend's message; the admin views and Listening.vue use it
in place of raw axios and fetch.

The router guard waited on the home query's loaded flag, which is never
set when that query fails, so /admin and /cv/jobs could hang. It now
awaits a standalone me query owned by the auth store, and homeData gains
a settled flag for widgets that only need to know the fetch finished.

The Vite proxy targets are configurable through VITE_PROXY_*, and
build:js runs the Vite build without wasm-pack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 14:39:19 +01:00
co-authored by Claude Opus 5.5
parent 71344a1f8d
commit d3f722d077
26 changed files with 1176 additions and 681 deletions
+73 -20
View File
@@ -1,10 +1,18 @@
/**
* Current user + login/logout mutations.
*
* `user` is populated two ways: mirrored from homeData.me (the shared home query
* also returns the session user), and set directly by logIn()/refreshToken().
* The watch is `immediate` so a store created after homeData has already loaded
* still picks up the user.
* `user` is populated three ways:
* - ensureLoaded(): a standalone `me` query, fired at most once per page load.
* The router guard awaits it, and so does the login page.
* - adoptSession(): stores/homeData.js hands over the `me` it got back from
* the home query, so the /stp page never needs the standalone query.
* - logIn() / refreshToken() / logOut(), which set it directly.
*
* This store deliberately does NOT import homeData. It used to mirror
* homeData.me with a watch, which meant that merely asking "who is signed in?"
* instantiated homeData and so fired the nine-field home query — Spotify, Steam
* and Gitea upstreams included — and the guard then had to wait on it. The
* dependency now points the other way: homeData pushes `me` in here.
*
* The JWTs themselves are never visible here — the backend sets access_token and
* refresh_token as HTTP-only cookies, so `loggedIn` is inferred purely from
@@ -12,28 +20,66 @@
*/
import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
import { useHomeDataStore } from "@/stores/homeData";
export const useAuthStore = defineStore("auth", () => {
const user = ref({});
const loggedIn = computed(() => !!user.value.username);
const homeData = useHomeDataStore();
// Mirror the `me` field from the shared home query. `immediate` so a store
// created after homeData loaded still sees the user. Only overwrite on a
// truthy `me` — a logged-out response is null and must not clobber a user
// that logIn() just set.
watch(
() => homeData.me,
(me) => {
if (me) {
user.value = me;
}
},
{ immediate: true },
);
// True once something has answered "who is signed in?" — the `me` query,
// the home query, or a login/logout. Until then an empty `user` means
// "unknown", not "signed out", which is the distinction the guard needs.
const resolved = ref(false);
// Bumped by every login/logout/refresh. A `me` answer that was requested
// before the bump describes the previous session, so it is dropped rather
// than allowed to sign a logged-out user back in (or the reverse).
let epoch = 0;
let pending = null;
function markSessionChanged() {
epoch++;
resolved.value = true;
}
/**
* Apply a `me` answer that was requested when the session was at
* `requestedAt` (a value from sessionEpoch()). Only a truthy `me` overwrites
* `user`: a signed-out answer is null and must not clobber a user that
* logIn() set while the request was in flight.
*/
function adoptSession(me, requestedAt = epoch) {
if (requestedAt !== epoch) return;
if (me) user.value = me;
resolved.value = true;
}
/** Token for adoptSession(): read it before issuing a query that returns `me`. */
function sessionEpoch() {
return epoch;
}
/**
* Resolve once the signed-in user is known, fetching `me` if nothing has
* supplied it yet. NEVER rejects and never hangs: a failed query settles as
* "not signed in", because the router guard awaits this and a navigation
* that never resolves is worse than a bounce to the login page. A failure is
* not remembered, so the next call tries again.
*/
function ensureLoaded() {
if (resolved.value) return Promise.resolve();
if (!pending) {
const requestedAt = epoch;
pending = gql(`query Me { me { id username admin } }`)
.then((data) => adoptSession(data.me, requestedAt))
.catch((err) => console.error("me query failed:", err))
.finally(() => {
pending = null;
});
}
return pending;
}
/** Clear the session cookies server-side, then blank the local user.
* Deliberately clears `user` even if the mutation fails. */
@@ -44,6 +90,7 @@ export const useAuthStore = defineStore("auth", () => {
console.error(err);
}
user.value = {};
markSessionChanged();
}
/** Log in and populate `user`. Swallows errors: on a bad password `user`
@@ -55,6 +102,7 @@ export const useAuthStore = defineStore("auth", () => {
{ input: { username, password } },
);
user.value = data.login.user;
markSessionChanged();
} catch (err) {
console.error(err);
}
@@ -83,6 +131,7 @@ export const useAuthStore = defineStore("auth", () => {
`mutation { refreshToken { user { id username admin } } }`,
);
user.value = data.refreshToken.user;
markSessionChanged();
} catch (err) {
console.log(err);
}
@@ -107,6 +156,10 @@ export const useAuthStore = defineStore("auth", () => {
loggedIn,
ensureLoaded,
adoptSession,
sessionEpoch,
logIn,
refreshToken,
logOut,
+123
View File
@@ -0,0 +1,123 @@
/**
* Factory for the "CRUD store" pattern shared by stores/places.js,
* jobApplications.js and jobAppReferences.js.
*
* Each of those is one GraphQL type with the schema's standard quartet — a list
* query, `create<Type>(input:)`, `update<Type>(id:, input:)` and
* `delete<Type>(id:)` — plus a local array that is patched after each mutation
* instead of being refetched. The operation and input-type names are derived
* from `type` because the schema is consistent about them
* (`Create<Type>Input`, `Update<Type>Input`); a type that breaks the convention
* should not be forced through here.
*
* `fields` is interpolated into every query and mutation so the selection set
* can never drift between them.
*
* Error contract, which callers rely on: fetch() never throws — it records the
* failure on `error` — because it is fired from lifecycle hooks with nothing to
* catch it. create/update/remove DO throw, so the form or row that triggered
* them can show the message and keep the user's typing.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
/**
* @param {string} id Pinia store id
* @param {object} options
* @param {string} options.type GraphQL type name, e.g. "Place"
* @param {string} options.list list query field, e.g. "places"
* @param {string} options.fields selection set shared by every operation
* @param {string} [options.itemsKey] name the array is exposed under (defaults
* to `list`); components import it by that name
* @param {"prepend"|"append"} [options.insert] where create() puts the new row
* locally, matching the order the list query returns
* @param {"object"|"boolean"} [options.deleteReturns] what the delete mutation
* returns. An object type needs a selection set and a scalar must not have
* one, so the mutation text differs; the schema has both kinds.
* @param {(ctx: object) => object} [options.extend] extra state/actions merged
* into the store; receives the base members
*/
export function createCrudStore(
id,
{
type,
list,
fields,
itemsKey = list,
insert = "prepend",
deleteReturns = "object",
extend,
},
) {
const deleteSelection = deleteReturns === "object" ? "{ id }" : "";
return defineStore(id, () => {
const items = ref([]);
const loaded = ref(false);
const loading = ref(false);
const error = ref(null);
/** Load the whole list. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
const data = await gql(`query ${type}List { ${list} { ${fields} } }`);
items.value = data[list] || [];
loaded.value = true;
error.value = null;
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
/** Create a row and add it locally. Throws on failure. */
async function create(input) {
const data = await gql(
`mutation Create${type}($input: Create${type}Input!) {
create${type}(input: $input) { ${fields} }
}`,
{ input },
);
const created = data[`create${type}`];
items.value =
insert === "append"
? [...items.value, created]
: [created, ...items.value];
return created;
}
/** Patch a row and replace it in the local list. Throws on failure. */
async function update(rowId, input) {
const data = await gql(
`mutation Update${type}($id: ID!, $input: Update${type}Input!) {
update${type}(id: $id, input: $input) { ${fields} }
}`,
{ id: rowId, input },
);
const updated = data[`update${type}`];
const idx = items.value.findIndex((item) => item.id === rowId);
if (idx >= 0) items.value[idx] = updated;
return updated;
}
/** Delete a row and drop it from the local list. Throws on failure. */
async function remove(rowId) {
await gql(
`mutation Delete${type}($id: ID!) { delete${type}(id: $id) ${deleteSelection} }`,
{ id: rowId },
);
items.value = items.value.filter((item) => item.id !== rowId);
}
const base = { loaded, loading, error, fetch, create, update, remove };
return {
[itemsKey]: items,
...base,
...(extend ? extend({ items, ...base }) : {}),
};
});
}
+28 -5
View File
@@ -4,22 +4,32 @@
* One GraphQL query fetches everything the /stp widgets need (posts, favorites,
* activities, Spotify, rowing, bookmarks, Gitea feed, Steam, current user) in a
* single round trip, instead of each widget issuing its own request. The
* per-domain stores (posts, favorites, activity, songs, steam, auth) are thin
* views over this one — they `watch` their slice of it rather than fetching.
* per-domain stores (posts, favorites, activity, songs, steam) are thin views
* over this one — they `watch` their slice of it rather than fetching. The
* session user is the exception: `me` is pushed into stores/auth.js, which owns
* it and can also fetch it alone (the router guard does not wait on this query).
*
* fetchAll() is called once at the bottom of the setup function, i.e. the first
* time any component calls useHomeDataStore(). That is why no component has to
* kick off the initial load, and why `loaded` is the flag the router guard waits
* on to know whether `me` has been resolved yet.
* kick off the initial load.
*
* Two flags, because "finished" and "succeeded" are different questions:
* `settled` — a fetch has completed, either way. Wait on / show a spinner
* against THIS; it always becomes true.
* `loaded` — a fetch has succeeded at least once, so the data refs are real.
* Anything that waited on `loaded` alone would wait forever when the query
* fails outright, which is how the router guard used to hang.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import axios from "axios";
import { useAuthStore } from "@/stores/auth";
export const useHomeDataStore = defineStore("homeData", () => {
const loaded = ref(false);
const settled = ref(false);
const error = ref(null);
const me = ref(null);
@@ -36,9 +46,14 @@ export const useHomeDataStore = defineStore("homeData", () => {
/**
* Fetch every home-page dataset in one GraphQL round trip, plus the radio
* liveness probe in parallel. Sets `loaded` on success and `error` on
* failure; never throws. Safe to call again to refresh.
* failure, and `settled` either way; never throws. Safe to call again to
* refresh.
*/
async function fetchAll() {
const auth = useAuthStore();
// Read before the request goes out: if the user logs in or out while it is
// in flight, the `me` it returns is stale and auth will ignore it.
const sessionAt = auth.sessionEpoch();
try {
const [data] = await Promise.all([
gql(`
@@ -65,10 +80,17 @@ export const useHomeDataStore = defineStore("homeData", () => {
gitFeed.value = data.giteaFeed || null;
steamStatus.value = data.steamStatus || null;
me.value = data.me || null;
// The home query already says who is signed in, so hand it to the auth
// store rather than have it issue its own `me` query on this page.
auth.adoptSession(me.value, sessionAt);
loaded.value = true;
// A refresh that works clears the failure a previous one left behind.
error.value = null;
} catch (err) {
console.error("HomeData fetch failed:", err);
error.value = err;
} finally {
settled.value = true;
}
}
@@ -91,6 +113,7 @@ export const useHomeDataStore = defineStore("homeData", () => {
return {
loaded,
settled,
error,
me,
bookmarks,
+21
View File
@@ -0,0 +1,21 @@
/**
* The "Quick Reference" snippets on /cv/jobs (reusable profile/experience text
* to paste into application forms) — CRUD built on createCrudStore().
*
* A separate table from the applications themselves; the two only share a page.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const REF_FIELDS = `id category label value sortOrder createdAt`;
export const useJobAppReferencesStore = createCrudStore("jobAppReferences", {
type: "JobAppReference",
list: "jobAppReferences",
itemsKey: "references",
fields: REF_FIELDS,
// The list comes back in sortOrder/creation order, so new rows go last.
insert: "append",
// deleteJobAppReference returns Boolean!, and errors for an id that is gone.
deleteReturns: "boolean",
});
+39
View File
@@ -0,0 +1,39 @@
/**
* Job applications for the tracker at /cv/jobs — CRUD built on
* createCrudStore(), plus the on-demand posting text.
*
* Admin-only on the server, and only that one page uses it, so nothing fetches
* it until the view mounts.
*/
import { createCrudStore } from "@/stores/createCrudStore";
import { gql } from "@/graphql";
// `description` is deliberately not here: it is the full text of the posting,
// tens of kilobytes a row, and is fetched per row when asked for.
const APP_FIELDS = `id jobTitle company location url status notes appliedAt createdAt updatedAt`;
export const useJobApplicationsStore = createCrudStore("jobApplications", {
type: "JobApplication",
list: "jobApplications",
itemsKey: "applications",
fields: APP_FIELDS,
insert: "prepend",
// deleteJobApplication returns Boolean!, and errors for an id that is gone.
deleteReturns: "boolean",
extend: () => ({
/**
* The captured posting text for one row; `""` when none was saved. Throws
* on failure. Not cached here: the view keeps its own per-visit cache, so
* returning to the page re-reads a posting the userscript may have
* replaced.
*/
async fetchDescription(id) {
const data = await gql(
`query JobDescription($id: ID!) { jobApplication(id: $id) { description } }`,
{ id },
);
return data.jobApplication?.description ?? "";
},
}),
});
+16 -79
View File
@@ -1,17 +1,13 @@
/**
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD.
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD,
* built on createCrudStore().
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
* fetches it lazily once the user is logged in. PLACE_FIELDS is interpolated into
* every query/mutation so the selection set can never drift between them.
* fetches it lazily once the user is logged in.
*/
import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import { createCrudStore } from "@/stores/createCrudStore";
// Shared selection set: interpolated into every query and mutation so they can
// never drift apart.
const PLACE_FIELDS = `
id
title
@@ -26,75 +22,16 @@ const PLACE_FIELDS = `
updatedAt
`;
export const usePlacesStore = defineStore("places", () => {
const places = ref([]);
const loaded = ref(false);
const loading = ref(false);
const error = ref(null);
/** Load all places into `places`. Records failures on `error` rather than throwing. */
async function fetch() {
loading.value = true;
try {
const data = await gql(`query Places { places { ${PLACE_FIELDS} } }`);
places.value = data.places || [];
loaded.value = true;
error.value = null;
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
/** Create a place and prepend it locally (newest first). Throws on failure. */
async function create(input) {
const data = await gql(
`mutation CreatePlace($input: CreatePlaceInput!) {
createPlace(input: $input) { ${PLACE_FIELDS} }
}`,
{ input },
);
places.value = [data.createPlace, ...places.value];
return data.createPlace;
}
/** Patch a place and replace it in the local list. Throws on failure. */
async function update(id, input) {
const data = await gql(
`mutation UpdatePlace($id: ID!, $input: UpdatePlaceInput!) {
updatePlace(id: $id, input: $input) { ${PLACE_FIELDS} }
}`,
{ id, input },
);
const idx = places.value.findIndex((p) => p.id === id);
if (idx >= 0) places.value[idx] = data.updatePlace;
return data.updatePlace;
}
/** Flip a place's `done` flag. */
async function toggleDone(place) {
return update(place.id, { done: !place.done });
}
/** Soft-delete a place and drop it from the local list. */
async function remove(id) {
await gql(
`mutation DeletePlace($id: ID!) { deletePlace(id: $id) { id } }`,
{ id },
);
places.value = places.value.filter((p) => p.id !== id);
}
return {
places,
loaded,
loading,
error,
fetch,
create,
update,
toggleDone,
remove,
};
export const usePlacesStore = createCrudStore("places", {
type: "Place",
list: "places",
fields: PLACE_FIELDS,
// The list query returns newest first, so a new place goes on top.
insert: "prepend",
// deletePlace returns the deleted Place, unlike the job tracker's deletes.
deleteReturns: "object",
extend: ({ update }) => ({
/** Flip a place's `done` flag. */
toggleDone: (place) => update(place.id, { done: !place.done }),
}),
});