gantt-board/scripts/lib/api_client.sh

50 lines
1.1 KiB
Bash
Executable File

#!/bin/bash
API_URL="${API_URL:-http://localhost:3000/api}"
COOKIE_FILE="${GANTT_COOKIE_FILE:-$HOME/.config/gantt-board/cookies.txt}"
ensure_cookie_store() {
mkdir -p "$(dirname "$COOKIE_FILE")"
touch "$COOKIE_FILE"
}
urlencode() {
jq -rn --arg v "$1" '$v|@uri'
}
api_call() {
local method="$1"
local endpoint="$2"
local data="${3:-}"
ensure_cookie_store
local url="${API_URL}${endpoint}"
local curl_opts=(-sS -w "\n%{http_code}" -X "$method" "$url" -H "Content-Type: application/json" -b "$COOKIE_FILE" -c "$COOKIE_FILE")
if [[ -n "$data" ]]; then
curl_opts+=(--data "$data")
fi
local response
response=$(curl "${curl_opts[@]}") || return 1
local http_code
http_code=$(echo "$response" | tail -n1)
local body
body=$(echo "$response" | sed '$d')
if [[ "$http_code" =~ ^2[0-9][0-9]$ ]]; then
echo "$body"
return 0
fi
if [[ "$http_code" == "401" ]]; then
echo "Unauthorized. Login first: ./gantt.sh auth login <email> <password>" >&2
fi
echo "API request failed ($method $endpoint) HTTP $http_code" >&2
echo "$body" | jq . 2>/dev/null >&2 || echo "$body" >&2
return 1
}