mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-17 17:25:13 +00:00
docs: Add Elixir SDK README with comprehensive API documentation and implement modular architecture with GenServer support
- Add README.md with installation instructions, architecture overview, and API examples for all SDK modules - Refactor TelecomSDK main module to use modular API clients (SubscribersAPI, UsageAPI, PaymentAPI, RatingPlanAPI, SystemAPI, GraphQLAPI) - Add AuthProvider class with API key and JWT token support (generate_jwt_token, validate_jwt_token methods) - Add HTTPClient base
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
defmodule TelecomSDK.AuthProvider do
|
||||
@moduledoc """
|
||||
Authentication provider for the Telecom SDK
|
||||
"""
|
||||
|
||||
defstruct [:api_key, :jwt_secret, :token_cache, :token_expiry]
|
||||
|
||||
def new(opts \\ []) do
|
||||
%__MODULE__{
|
||||
api_key: Keyword.get(opts, :api_key),
|
||||
jwt_secret: Keyword.get(opts, :jwt_secret),
|
||||
token_cache: nil,
|
||||
token_expiry: nil
|
||||
}
|
||||
end
|
||||
|
||||
def get_headers(%__MODULE__{api_key: api_key, token_cache: token_cache, token_expiry: token_expiry}) do
|
||||
headers = %{
|
||||
"Content-Type" => "application/json",
|
||||
"User-Agent" => "Telecom-Elixir-SDK/1.0.0"
|
||||
}
|
||||
|
||||
headers = if api_key, do: Map.put(headers, "X-API-Key", api_key), else: headers
|
||||
|
||||
if token_cache && token_valid?(token_expiry) do
|
||||
Map.put(headers, "Authorization", "Bearer #{token_cache}")
|
||||
else
|
||||
headers
|
||||
end
|
||||
end
|
||||
|
||||
def generate_jwt_token(%__MODULE__{jwt_secret: jwt_secret} = auth, user_id, expiry_hours \\ 24, additional_claims \\ %{}) do
|
||||
unless jwt_secret, do: raise(ArgumentError, "JWT secret not configured")
|
||||
|
||||
now = System.system_time(:second)
|
||||
exp = now + (expiry_hours * 3600)
|
||||
|
||||
claims = %{
|
||||
"sub" => user_id,
|
||||
"exp" => exp,
|
||||
"iat" => now
|
||||
}
|
||||
|> Map.merge(additional_claims)
|
||||
|
||||
header = %{"alg" => "HS256", "typ" => "JWT"}
|
||||
|
||||
encoded_header = base64_url_encode(header)
|
||||
encoded_payload = base64_url_encode(claims)
|
||||
signature = sign("#{encoded_header}.#{encoded_payload}", jwt_secret)
|
||||
|
||||
token = "#{encoded_header}.#{encoded_payload}.#{signature}"
|
||||
|
||||
%{auth | token_cache: token, token_expiry: exp}
|
||||
end
|
||||
|
||||
def validate_jwt_token(%__MODULE__{jwt_secret: jwt_secret}, token) do
|
||||
unless jwt_secret, do: raise(ArgumentError, "JWT secret not configured")
|
||||
|
||||
parts = String.split(token, ".")
|
||||
unless length(parts) == 3, do: raise(ArgumentError, "Invalid token format")
|
||||
|
||||
[encoded_header, encoded_payload, signature] = parts
|
||||
expected_signature = sign("#{encoded_header}.#{encoded_payload}", jwt_secret)
|
||||
|
||||
unless signature == expected_signature, do: raise(ArgumentError, "Invalid token signature")
|
||||
|
||||
case base64_url_decode(encoded_payload) do
|
||||
{:ok, payload_bytes} ->
|
||||
case Jason.decode(payload_bytes) do
|
||||
{:ok, payload} ->
|
||||
if payload["exp"] && payload["exp"] < System.system_time(:second) do
|
||||
raise(ArgumentError, "Token has expired")
|
||||
end
|
||||
payload
|
||||
{:error, _} -> raise(ArgumentError, "Failed to decode payload")
|
||||
end
|
||||
{:error, _} -> raise(ArgumentError, "Failed to decode payload")
|
||||
end
|
||||
end
|
||||
|
||||
def clear_token_cache(auth) do
|
||||
%{auth | token_cache: nil, token_expiry: nil}
|
||||
end
|
||||
|
||||
defp token_valid?(nil), do: false
|
||||
defp token_valid?(expiry), do: System.system_time(:second) < expiry
|
||||
|
||||
defp base64_url_encode(data) do
|
||||
json = Jason.encode!(data)
|
||||
json
|
||||
|> Base.url_encode64(padding: false)
|
||||
end
|
||||
|
||||
defp base64_url_decode(data) do
|
||||
# Add padding if needed
|
||||
padded_data = data <> String.duplicate("=", rem(4 - rem(String.length(data), 4), 4))
|
||||
Base.url_decode64(padded_data)
|
||||
end
|
||||
|
||||
defp sign(data, secret) do
|
||||
:crypto.mac(:hmac, :sha256, secret, data)
|
||||
|> Base.url_encode64(padding: false)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,17 @@
|
||||
defmodule TelecomSDK.GraphQLAPI do
|
||||
@moduledoc """
|
||||
API for GraphQL queries
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def execute(api, query, variables \\ nil) do
|
||||
request = %{query: query}
|
||||
request = if variables, do: Map.put(request, :variables, variables), else: request
|
||||
TelecomSDK.HTTPClient.post(api.client, "/graphql", request)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
defmodule TelecomSDK.HTTPClient do
|
||||
@moduledoc """
|
||||
HTTP client for making API requests
|
||||
"""
|
||||
|
||||
defstruct [:base_url, :auth_provider, :timeout, :max_retries, :retry_delay, :enable_logging]
|
||||
|
||||
def new(base_url, auth_provider, opts \\ []) do
|
||||
%__MODULE__{
|
||||
base_url: base_url,
|
||||
auth_provider: auth_provider,
|
||||
timeout: Keyword.get(opts, :timeout, 30_000),
|
||||
max_retries: Keyword.get(opts, :max_retries, 3),
|
||||
retry_delay: Keyword.get(opts, :retry_delay, 1_000),
|
||||
enable_logging: Keyword.get(opts, :enable_logging, false)
|
||||
}
|
||||
end
|
||||
|
||||
def get(client, path, params \\ %{}) do
|
||||
request(client, "GET", path, nil, params)
|
||||
end
|
||||
|
||||
def post(client, path, body \\ nil) do
|
||||
request(client, "POST", path, body, nil)
|
||||
end
|
||||
|
||||
def put(client, path, body \\ nil) do
|
||||
request(client, "PUT", path, body, nil)
|
||||
end
|
||||
|
||||
def delete(client, path) do
|
||||
request(client, "DELETE", path, nil, nil)
|
||||
end
|
||||
|
||||
defp request(client, method, path, body, params) do
|
||||
url = client.base_url <> path
|
||||
headers = TelecomSDK.AuthProvider.get_headers(client.auth_provider)
|
||||
|
||||
opts = [
|
||||
timeout: client.timeout,
|
||||
recv_timeout: client.timeout
|
||||
]
|
||||
|
||||
opts = if params != %{}, do: Keyword.put(opts, :params, params), else: opts
|
||||
opts = if body, do: Keyword.put(opts, :body, Jason.encode!(body)), else: opts
|
||||
|
||||
last_error = nil
|
||||
|
||||
Enum.reduce_while(0..client.max_retries, nil, fn attempt, _acc ->
|
||||
case do_request(method, url, headers, opts) do
|
||||
{:ok, response} ->
|
||||
case handle_response_errors(response) do
|
||||
:ok -> {:halt, {:ok, Jason.decode!(response.body)}}
|
||||
{:error, error} -> {:halt, {:error, error}}
|
||||
end
|
||||
{:error, error} ->
|
||||
if attempt < client.max_retries do
|
||||
Process.sleep(client.retry_delay * round(:math.pow(2, attempt)))
|
||||
{:cont, error}
|
||||
else
|
||||
{:halt, {:error, error}}
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp do_request(method, url, headers, opts) do
|
||||
case HTTPoison.request(method, url, Keyword.get(opts, :body), headers, opts) do
|
||||
{:ok, response} -> {:ok, response}
|
||||
{:error, error} -> {:error, error}
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_response_errors(%{status_code: status}) when status >= 200 and status < 300, do: :ok
|
||||
defp handle_response_errors(%{status_code: 401}), do: {:error, :authentication_failed}
|
||||
defp handle_response_errors(%{status_code: 429}), do: {:error, :rate_limit_exceeded}
|
||||
defp handle_response_errors(%{status_code: status}) when status >= 400 and status < 500, do: {:error, {:client_error, status}}
|
||||
defp handle_response_errors(%{status_code: status}) when status >= 500, do: {:error, {:server_error, status}}
|
||||
|
||||
def close(_client) do
|
||||
# HTTPoison doesn't need explicit cleanup
|
||||
:ok
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
defmodule TelecomSDK.PaymentAPI do
|
||||
@moduledoc """
|
||||
API for payment management
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def create_transaction(api, request) do
|
||||
TelecomSDK.HTTPClient.post(api.client, "/v1/payments/transactions", request)
|
||||
end
|
||||
|
||||
def get_transaction(api, transaction_id) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/payments/transactions/#{transaction_id}")
|
||||
end
|
||||
|
||||
def list_transactions(api, opts \\ []) do
|
||||
params = %{
|
||||
page: Keyword.get(opts, :page, 1),
|
||||
page_size: Keyword.get(opts, :page_size, 50)
|
||||
}
|
||||
|
||||
params = if Keyword.get(opts, :subscriber_id), do: Map.put(params, :subscriber_id, Keyword.get(opts, :subscriber_id)), else: params
|
||||
params = if Keyword.get(opts, :status), do: Map.put(params, :status, Keyword.get(opts, :status)), else: params
|
||||
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/payments/transactions", params)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
defmodule TelecomSDK.RatingPlanAPI do
|
||||
@moduledoc """
|
||||
API for rating plan management
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def list(api) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/rating-plans")
|
||||
end
|
||||
|
||||
def get(api, plan_id) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/rating-plans/#{plan_id}")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,41 @@
|
||||
defmodule TelecomSDK.SubscriberAPI do
|
||||
@moduledoc """
|
||||
API for subscriber management
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def get(api, id) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/subscribers/#{id}")
|
||||
end
|
||||
|
||||
def list(api, page \\ 1, page_size \\ 50, status \\ nil) do
|
||||
params = %{page: page, page_size: page_size}
|
||||
params = if status, do: Map.put(params, :status, status), else: params
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/subscribers", params)
|
||||
end
|
||||
|
||||
def create(api, request) do
|
||||
TelecomSDK.HTTPClient.post(api.client, "/v1/subscribers", request)
|
||||
end
|
||||
|
||||
def update(api, id, request) do
|
||||
TelecomSDK.HTTPClient.put(api.client, "/v1/subscribers/#{id}", request)
|
||||
end
|
||||
|
||||
def delete(api, id) do
|
||||
TelecomSDK.HTTPClient.delete(api.client, "/v1/subscribers/#{id}")
|
||||
end
|
||||
|
||||
def suspend(api, id) do
|
||||
TelecomSDK.HTTPClient.post(api.client, "/v1/subscribers/#{id}/suspend")
|
||||
end
|
||||
|
||||
def activate(api, id) do
|
||||
TelecomSDK.HTTPClient.post(api.client, "/v1/subscribers/#{id}/activate")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
defmodule TelecomSDK.SystemAPI do
|
||||
@moduledoc """
|
||||
API for system management
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def get_stats(api) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/system/stats")
|
||||
end
|
||||
|
||||
def get_health(api) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/health")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,37 @@
|
||||
defmodule TelecomSDK.UsageAPI do
|
||||
@moduledoc """
|
||||
API for usage management
|
||||
"""
|
||||
|
||||
defstruct [:client]
|
||||
|
||||
def new(client) do
|
||||
%__MODULE__{client: client}
|
||||
end
|
||||
|
||||
def get_stats(api, subscriber_id, start_date, end_date) do
|
||||
params = %{
|
||||
start_date: DateTime.to_iso8601(start_date),
|
||||
end_date: DateTime.to_iso8601(end_date)
|
||||
}
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/subscribers/#{subscriber_id}/usage", params)
|
||||
end
|
||||
|
||||
def list_events(api, opts \\ []) do
|
||||
params = %{
|
||||
page: Keyword.get(opts, :page, 1),
|
||||
page_size: Keyword.get(opts, :page_size, 50)
|
||||
}
|
||||
|
||||
params = if Keyword.get(opts, :subscriber_id), do: Map.put(params, :subscriber_id, Keyword.get(opts, :subscriber_id)), else: params
|
||||
params = if Keyword.get(opts, :usage_type), do: Map.put(params, :usage_type, Keyword.get(opts, :usage_type)), else: params
|
||||
params = if Keyword.get(opts, :start_date), do: Map.put(params, :start_date, DateTime.to_iso8601(Keyword.get(opts, :start_date))), else: params
|
||||
params = if Keyword.get(opts, :end_date), do: Map.put(params, :end_date, DateTime.to_iso8601(Keyword.get(opts, :end_date))), else: params
|
||||
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/usage/events", params)
|
||||
end
|
||||
|
||||
def get_realtime(api, subscriber_id) do
|
||||
TelecomSDK.HTTPClient.get(api.client, "/v1/subscribers/#{subscriber_id}/realtime")
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user