import { createReducer, on } from '@ngrx/store'; import { ApiKey, CreateApiKeyResponse } from '../api-keys/models/api-key.model'; import * as ApiKeyActions from '../actions/api-key.actions'; export interface ApiKeyState { keys: ApiKey[]; loading: boolean; error: string | null; newKey: CreateApiKeyResponse | null; // holds the just-created key (plain key visible once) } export const initialState: ApiKeyState = { keys: [], loading: false, error: null, newKey: null, }; export const FEATURE_KEY = 'apiKey'; export const apiKeyReducer = createReducer( initialState, on(ApiKeyActions.loadApiKeys, (state) => ({ ...state, loading: true, error: null })), on(ApiKeyActions.loadApiKeysSuccess, (state, { keys }) => ({ ...state, keys, loading: false })), on(ApiKeyActions.loadApiKeysFailure, (state, { error }) => ({ ...state, loading: false, error })), on(ApiKeyActions.createApiKey, (state) => ({ ...state, loading: true, error: null })), on(ApiKeyActions.createApiKeySuccess, (state, { response }) => ({ ...state, loading: false, newKey: response, // Add new key to list (without the plain key field) keys: [{ _id: response._id, label: response.label, prefix: response.prefix, active: response.active, service: response.service, managedBy: response.managedBy, createdAt: response.createdAt, owner: response.owner }, ...state.keys], })), on(ApiKeyActions.createApiKeyFailure, (state, { error }) => ({ ...state, loading: false, error })), on(ApiKeyActions.revokeApiKey, (state) => ({ ...state, loading: true, error: null })), on(ApiKeyActions.revokeApiKeySuccess, (state, { keyId }) => ({ ...state, loading: false, keys: state.keys.map(k => k._id === keyId ? { ...k, active: false } : k), })), on(ApiKeyActions.revokeApiKeyFailure, (state, { error }) => ({ ...state, loading: false, error })), on(ApiKeyActions.deleteApiKey, (state) => ({ ...state, loading: true, error: null })), on(ApiKeyActions.deleteApiKeySuccess, (state, { keyId }) => ({ ...state, loading: false, keys: state.keys.filter(k => k._id !== keyId), })), on(ApiKeyActions.deleteApiKeyFailure, (state, { error }) => ({ ...state, loading: false, error })), on(ApiKeyActions.regenerateApiKey, (state) => ({ ...state, loading: true, error: null })), on(ApiKeyActions.regenerateApiKeySuccess, (state, { response }) => ({ ...state, loading: false, newKey: response, keys: state.keys.map(k => k._id === response._id ? { ...k, prefix: response.prefix, active: true } : k), })), on(ApiKeyActions.regenerateApiKeyFailure, (state, { error }) => ({ ...state, loading: false, error })), on(ApiKeyActions.dismissNewKey, (state) => ({ ...state, newKey: null })), );