Source: stores/message.js

/*
 * Copyright © 2019-2025 The CTAN Team and individual authors
 *
 * This file is distributed under the 3-clause BSD license.
 * See file LICENSE for details.
 */
import { defineStore } from 'pinia'

/**
 * This is the store for messages of the CTAN portal.
 *
 * @author Gerd Neugebauer <gene@ctan.org>
 */
export const useMessageStore = defineStore("message", {
  state: () => ({
    /**
     * The counter for authors packages and topics.
     */
    count: {
      done: false
    },
    /**
     * The error message.
     */
    error: null,
    /**
     * The supported langugaes.
     */
    languages: [],
    /**
     * The loading indicator. This is a counter. It is incremented when a
     * loading action starts and decremented afterwards.
     */
    loading: 0,
    /**
     * The list of messages.
     */
    motd: [],
    /**
     * The name of the application.
     */
    name: '',
    /**
     * The current version from the server.
     */
    version: ''
  }),

  getters: {
    /**
     * Determine whether loading is in progress.
     */
    isLoading: (state) => state.loading !== 0 
  },

  actions: {
    /**
     * Another back-end communication is in progress.
     */
    beginLoading () {
      this.loading++
    },
    /**
     * Another back-end communication has ended.
     */
    endLoading () {
      this.loading--
    },
    /**
     * Initialise.
     * @param i18n the vue:i18n library
     */
    init (i18n) {
      this.load(i18n.locale)
    },
    /**
     * Load the messages from the back-end.
     * @param locale the language code
     */
    async load(locale) {
      this.beginLoading()
      return $fetch('/api/3.0/site/config', {
        query: {
          lang: locale
        }
      })
        .then((data) => {
          this.name = data.name
          this.version = data.version
          this.languages = data.languages
          this.motd = data.motd
          this.count = {
            done: true,
            authors: data.authors,
            pkgs: data.pkgs,
            topics: data.topics
          }
        })
        .catch ((error) => {
          this.reportError(error)
        })
        .finally ( () => {
          this.endLoading()
        })
    },
    /**
     * Do something with the error.
     * @param error the error
     */
    reportError (error) {

      switch (error.statusCode) {
      case 400:
      case 500:
      case 502:
      case 504:
        this.error = error
        break;
      default:
        throw showError({
          fatal: true,
          statusCode: error.statusCode,
          message: error.message
        })
      }
    }
  }
})