class Appwrite::Client

Public Class Methods

new() click to toggle source
# File lib/appwrite/client.rb, line 11
def initialize
    @chunk_size = 5*1024*1024
    @headers = {
        'user-agent' => RUBY_PLATFORM + ':ruby-' + RUBY_VERSION,
        'x-sdk-version' => 'appwrite:ruby:4.1.0',                
        'X-Appwrite-Response-Format' => '0.13.0'
    }
    @endpoint = 'https://HOSTNAME/v1'
end

Public Instance Methods

add_header(key, value) click to toggle source

Add Header

@param [String] key The key for the header to add @param [String] value The value for the header to add

@return [self]

# File lib/appwrite/client.rb, line 100
def add_header(key, value)
    @headers[key.downcase] = value

    self
end
call( method:, path: '', headers: {}, params: {}, response_type: nil ) click to toggle source

Send the HTTP request.

@param [String] method The HTTP method for the request @param [String] path The path for the request @param [Hash] headers The headers to send with the request @param [Hash] params The parameters to send with the request @param [Class] response_type The type of response to return

@return [self]

# File lib/appwrite/client.rb, line 115
def call(
    method:,
    path: '',
    headers: {},
    params: {},
    response_type: nil
)
    uri = URI.parse(@endpoint + path + ((method == "GET" && params.length) ? '?' + encode(params) : ''))

    fetch(method, uri, headers, params, response_type)
end
chunked_upload( path:, headers:, params:, param_name: '', id_param_name: nil, on_progress: nil, response_type: nil ) click to toggle source
# File lib/appwrite/client.rb, line 127
def chunked_upload(
    path:,
    headers:,
    params:,
    param_name: '',
    id_param_name: nil,
    on_progress: nil,
    response_type: nil
)
    file_path = params[param_name.to_sym]
    size = ::File.size(file_path)

    if size < @chunk_size
        slice = ::File.read(file_path)
        params[param_name] = File.new(file_path, slice)
        return call(
            method: 'POST',
            path: path,
            headers: headers,
            params: params,
            response_type: response_type,
        )
    end

    offset = 0
    id_param_name = id_param_name.to_sym if id_param_name
    if id_param_name&.empty? == false && params[id_param_name] != "unique()"
        # Make a request to check if a file already exists
        current = call(
            method: "GET",
            path: "#{path}/#{params[id_param_name]}",
            headers: headers,
            params: {}
        )
        chunks_uploaded = current['chunksUploaded'].to_i
        offset = [size, (chunks_uploaded * @chunk_size)].min
    end

    while offset < size
        slice = IO.read(file_path, @chunk_size, offset)

        params[param_name] = File.new(file_path, slice)
        headers['content-range'] = "bytes #{offset}-#{[offset + @chunk_size - 1, size].min}/#{size}"

        result = call(
            method: 'POST',
            path: path,
            headers: headers,
            params: params,
        )

        offset += @chunk_size

        if defined? result['$id']
            headers['x-Appwrite-id'] = result['$id']
        end

        on_progress.call({
            id: result['$id'],
            progress: ([offset, size].min).to_f/size.to_f * 100.0,
            size_uploaded: [offset, size].min,
            chunks_total: result['chunksTotal'],
            chunks_uploaded: result['chunksUploaded']
        }) unless on_progress.nil?
    end

    return result unless response_type.respond_to?("from")

    response_type.from(map: result)
end
set_endpoint(endpoint) click to toggle source

Set endpoint.

@param [String] endpoint The endpoint to set

@return [self]

# File lib/appwrite/client.rb, line 76
def set_endpoint(endpoint)
    @endpoint = endpoint
    
    self
end
set_jwt(value) click to toggle source

Set JWT

Your secret JSON Web Token

@param [String] value The value to set for the JWT header

@return [self]

# File lib/appwrite/client.rb, line 54
def set_jwt(value)
    add_header('x-appwrite-jwt', value)

    self
end
set_key(value) click to toggle source

Set Key

Your secret API key

@param [String] value The value to set for the Key header

@return [self]

# File lib/appwrite/client.rb, line 41
def set_key(value)
    add_header('x-appwrite-key', value)

    self
end
set_locale(value) click to toggle source

Set Locale

@param [String] value The value to set for the Locale header

@return [self]

# File lib/appwrite/client.rb, line 65
def set_locale(value)
    add_header('x-appwrite-locale', value)

    self
end
set_project(value) click to toggle source

Set Project

Your project ID

@param [String] value The value to set for the Project header

@return [self]

# File lib/appwrite/client.rb, line 28
def set_project(value)
    add_header('x-appwrite-project', value)

    self
end
set_self_signed(self_signed = true) click to toggle source

Set self signed.

@param [String] self_signed Whether to allow self signed certificates.

@return [self]

# File lib/appwrite/client.rb, line 87
def set_self_signed(self_signed = true)
    @self_signed = self_signed

    self
end

Private Instance Methods

append_key(root_key, key) click to toggle source
# File lib/appwrite/client.rb, line 306
def append_key(root_key, key)
    root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
end
encode(value, key = nil) click to toggle source
# File lib/appwrite/client.rb, line 296
def encode(value, key = nil)
    case value
    when Hash  then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
    when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
    when nil   then ''
    else            
    "#{key}=#{CGI.escape(value.to_s)}" 
    end
end
encode_form_data(value, key=nil) click to toggle source
# File lib/appwrite/client.rb, line 272
def encode_form_data(value, key=nil)
    case value
    when Hash
        value.map { |k,v| encode_form_data(v,k) }.join
    when Array
        value.map { |v| encode_form_data(v, "#{key}[]") }.join
    when nil
        ''
    else
        post_body = []
        if value.instance_of? File
            post_body << "Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{value.name}\"\r\n"
            post_body << "Content-Type: #{value.mime_type}\r\n\r\n"
            post_body << value.content
            post_body << "\r\n--#{@boundary}--\r\n"
        else          
            post_body << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
            post_body << "#{value.to_s}" 
            post_body << "\r\n--#{@boundary}\r\n"
        end
        post_body.join
    end
end
fetch( method, uri, headers, params, response_type = nil, limit = 5 ) click to toggle source
# File lib/appwrite/client.rb, line 200
def fetch(
    method,
    uri,
    headers,
    params,
    response_type = nil,
    limit = 5
)
    raise ArgumentError, 'Too Many HTTP Redirects' if limit == 0

    @http = Net::HTTP.new(uri.host, uri.port) unless defined? @http
    @http.use_ssl = !@self_signed
    payload = ''
    
    headers = @headers.merge(headers)

    @boundary = "----A30#3ad1"
    if method != "GET"
        case headers[:'content-type']
            when 'application/json'
                payload = params.to_json
            when 'multipart/form-data'
                payload = "--#{@boundary}\r\n" + encode_form_data(params)
                headers[:'content-type'] = "multipart/form-data; boundary=#{@boundary}"
            else
                payload = encode(params)
        end
    end

    begin
        response = @http.send_request(method, uri.request_uri, payload, headers)
    rescue => error
        raise Appwrite::Exception.new(error.message)
    end
    
    # Handle Redirects
    if response.class == Net::HTTPRedirection || response.class == Net::HTTPMovedPermanently
        location = response['location']
        uri = URI.parse(uri.scheme + "://" + uri.host + "" + location)
        
        return fetch(method, uri, headers, {}, response_type, limit - 1)
    end

    if response.content_type == 'application/json'
        begin
            result = JSON.parse(response.body)
        rescue JSON::ParserError => e
            raise Appwrite::Exception.new(response.body, response.code, nil, response)
        end

        if response.code.to_i >= 400
            raise Appwrite::Exception.new(result['message'], result['status'], result['type'], result)
        end

        unless response_type.respond_to?("from")
            return result
        end

        return response_type.from(map: result)
    end

    if response.code.to_i >= 400
        raise Appwrite::Exception.new(response.body, response.code, response)
    end

    if response.respond_to?("body_permitted?")
        return response.body if response.body_permitted?
    end

    return response
end