grist-grist 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e77352236c1dc254aaf3ba8b1babd19136beb839d41ab5efc9832afa84e661ed
4
+ data.tar.gz: 437e6530adefb67149485435eb3c74697f4de942919a856e7bde21f468c713c8
5
+ SHA512:
6
+ metadata.gz: 81734bd4a76545fb675bce6bb4ebe383fabd0e1fcd885b8a173d6a264c7019af7eb432d8cba509c97801267f5fe188b0fe808a81aa0ba3879b3b96a42d290efb
7
+ data.tar.gz: 5771be9c324fc9194f925b3e35175515440f4ae5c4284063b3f33b2ec221525d111fa2ab80fdc405dc4ddc533b10c737e4a1e76ddd7925ff7fddfb10cad37bb0
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-04-01
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at 26109239+Quentinchampenois@users.noreply.github.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 quentinchampenois
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # Grist::Ruby
2
+
3
+ This gem provides a Ruby client for the Grist API.
4
+
5
+ ⚠️ Library isn't ready to use, not actively maintained
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'grist'
13
+ ```
14
+
15
+ And install the gem:
16
+
17
+ ```bash
18
+ $ bundle install
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ See `examples/main.rb`
24
+
25
+ ## Development
26
+
27
+ 1. Start a Grist instance locally
28
+ ```bash
29
+ $ docker compose up -d
30
+ ```
31
+
32
+ ### Playground using IRB
33
+ Then start the ruby console
34
+ ```
35
+ $ GRIST_API_KEY=<GRIST_API_KEY> GRIST_API_URL=http://localhost:8484/api bundle exec bin/console
36
+ ```
37
+ * GRIST_API_KEY can be found directly into your account at : http://localhost:8484/o/docs/account
38
+
39
+ You can now interact with Grist, example : `$ Grist::Type::Organization.all`
40
+
41
+ ### Using existing examples
42
+
43
+ * First example will create 1 Workspace, with 2 Documents, with 3 tables into document 'demo'.
44
+ how to use it
45
+ ```bash
46
+ $ GRIST_API_KEY=a61b5bc73849e715dd9ebec0216230924021d6b6 GRIST_API_URL=http://localhost:8484/api bundle exec examples/main.r
47
+ ```
48
+
49
+ * `GRIST_API_URL` base url must contain `/api`
50
+
51
+ * Second example will update records
52
+ ```bash
53
+ GRIST_ORG_NAME=<ORGANIZATION_NAME> GRIST_API_KEY=a61b5bc73849e715dd9ebec0216230924021d6b6 GRIST_API_URL=http://localhost:8484/api bundle exec examples/update.rb
54
+ ```
55
+
56
+ * `ORGANIZATION_NAME` is case-sensitive
57
+
58
+
59
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
60
+
61
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
62
+
63
+ ## Contributing
64
+
65
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/grist-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/grist-ruby/blob/main/CODE_OF_CONDUCT.md).
66
+
67
+ ## License
68
+
69
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
70
+
71
+ ## Code of Conduct
72
+
73
+ Everyone interacting in the Grist::Ruby project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/grist-ruby/blob/main/CODE_OF_CONDUCT.md).
74
+
75
+ ## Resources
76
+ * https://support.getgrist.com/api/#tag/records/operation/addRecords
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,11 @@
1
+ version: '3'
2
+
3
+ services:
4
+ app:
5
+ image: gristlabs/grist:latest
6
+ ports:
7
+ - "8484:8484"
8
+ volumes:
9
+ - ./volumes/data:/persist:rw
10
+ environment:
11
+ - GRIST_SESSION_SECRET=secret
data/examples/main.rb ADDED
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "grist"
6
+ require "byebug"
7
+
8
+ raise ArgumentError, "You must provide env var : 'GRIST_API_KEY'" if ENV.fetch("GRIST_API_KEY", "").empty?
9
+ raise ArgumentError, "You must provide env var : 'GRIST_API_URL'" if ENV.fetch("GRIST_API_URL", "").empty?
10
+
11
+ orgs = Grist::Type::Organization.all
12
+ org = orgs.last
13
+
14
+ if org.nil?
15
+ puts "No organization present"
16
+ exit 0
17
+ end
18
+
19
+ puts "Org: #{org.name} - ID: #{org.id}"
20
+
21
+ ws_name = "Workspace N°#{rand(1_000)}"
22
+ puts "Creating workspace #{ws_name}..."
23
+ ws = org.create_workspace({ name: ws_name })
24
+
25
+ puts "Creating document 'demo' into workspace '#{ws_name}'..."
26
+ doc = ws.create_doc({
27
+ name: "Demo",
28
+ isPinned: true
29
+ })
30
+
31
+ puts "Creating document 'Github' into workspace '#{ws_name}'"
32
+ ws.create_doc({
33
+ name: "Github",
34
+ isPinned: false
35
+ })
36
+
37
+ puts "Creating tables for document 'demo' into workspace '#{ws_name}'..."
38
+ doc.create_tables({
39
+ "tables" => [
40
+ { "id" => "Community gems",
41
+ "columns" => [
42
+ { "id" => "name", "fields" => { "label" => "Gem name" } },
43
+ { "id" => "description", "fields" => { "label" => "Description" } },
44
+ { "id" => "link", "fields" => { "label" => "RubyGems link" } }
45
+ ] }
46
+ ]
47
+ })
48
+
49
+ puts "Creating tables for document 'demo' into workspace '#{ws_name}'..."
50
+ doc.create_tables({
51
+ "tables" => [
52
+ { "id" => "Standard library",
53
+ "columns" => [
54
+ { "id" => "name", "fields" => { "label" => "Library name" } },
55
+ { "id" => "url", "fields" => { "label" => "Source code public URL" } },
56
+ { "id" => "version", "fields" => { "label" => "Latest version" } }
57
+ ] }
58
+ ]
59
+ })
60
+
61
+ doc = ws.docs.first
62
+ tables = doc.tables
63
+
64
+ puts "Tables:"
65
+ tables.each do |table|
66
+ puts table.id
67
+ puts "Total records : #{table.records.count}"
68
+ end
69
+
70
+ table = tables.last
71
+
72
+ puts "Creating records into table from doc 'demo' into workspace '#{ws_name}'..."
73
+ table.create_records("records" => [
74
+ {
75
+ "fields" => {
76
+ "name" => "did_you_mean",
77
+ "url" => "https://github.com/ruby/did_you_mean",
78
+ "version" => "v2.0.0"
79
+ }
80
+ }
81
+ ])
82
+
83
+ puts "Terminated, go check at http://localhost:8484/o/demo"
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "grist"
6
+ require "byebug"
7
+
8
+ raise ArgumentError, "You must provide env var : 'GRIST_API_KEY'" if ENV.fetch("GRIST_API_KEY", "").empty?
9
+ raise ArgumentError, "You must provide env var : 'GRIST_API_URL'" if ENV.fetch("GRIST_API_URL", "").empty?
10
+
11
+ TABLE_NAME = "Open_source_software"
12
+
13
+ org_name = ENV.fetch("GRIST_ORG_NAME", "")
14
+ orgs = Grist::Type::Organization.all
15
+ org = orgs.find { |org| org.name == org_name }
16
+
17
+ if org&.workspaces&.empty?
18
+ puts "No workspaces found in organization #{org.name}. Creating a new one..."
19
+ ws = org.create_workspace({ name: "Grist Ruby" })
20
+ puts "Workspace created: #{ws.name} - ID: #{ws.id}"
21
+ else
22
+ ws = org&.workspaces&.last
23
+ puts "Workspaces found in organization #{org.name}. Using the last one '#{ws.name}'..."
24
+ end
25
+
26
+ puts "Workspace ID: #{ws.id}"
27
+ puts "Workspace Name: #{ws.name}"
28
+
29
+ if ws.docs.empty?
30
+ puts "No docs found in workspace #{ws.name}. Creating a new one..."
31
+ doc = ws.create_doc({ name: "Getting started" })
32
+ puts "Doc created: #{doc.name} - ID: #{doc.id}"
33
+ else
34
+ doc = ws.docs.last
35
+ puts "Docs found in workspace #{ws.name}. Using the last one '#{doc.name}'..."
36
+ end
37
+
38
+ puts "Doc ID: #{doc.id}"
39
+ puts "Doc Name: #{doc.name}"
40
+
41
+ table = doc.tables.find { |t| t.id == TABLE_NAME }
42
+ if !table.nil?
43
+ puts "Table found in doc #{doc.name}. Using the last one '#{table.id}'..."
44
+ puts "Table ID: #{table.id}"
45
+ else
46
+ puts "No tables found in doc #{doc.name}. Creating a new one..."
47
+ new_table = Grist::Type::Table.new("id" => TABLE_NAME, "columns" => [
48
+ { "id" => "name", "fields" => { "label" => "Software name" } },
49
+ { "id" => "description", "fields" => { "label" => "Description" } },
50
+ { "id" => "link", "fields" => { "label" => "Source code link" } }
51
+ ])
52
+ table = doc.create_tables("tables" => [new_table.to_hash])[0]
53
+ puts "Table created ID: #{table&.id}"
54
+ end
55
+
56
+ # TODO: WIP
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grist
4
+ module Accessible
5
+ def access
6
+ id = instance_variable_get("@id")
7
+ request(:get, "#{path}/#{id}/access")
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grist
4
+ module ApiRoutes
5
+ ### ORGANIZATIONS
6
+ ORG_ALL = "https://{gristhost}/api/orgs"
7
+ ORG_FIND = "https://{gristhost}/api/orgs/{orgId}"
8
+ ORG_UPDATE = "https://{gristhost}/api/orgs/{orgId}"
9
+ ORG_DELETE = "https://{gristhost}/api/orgs/{orgId}"
10
+ # ORG ACCESS
11
+ ORG_ACCESS_ALL = "https://{gristhost}/api/orgs/{orgId}/access"
12
+ ORG_ACCESS_UPDATE = "https://{gristhost}/api/orgs/{orgId}/access"
13
+ # ORG WORKSPACE
14
+ WORKSPACE_ALL = "https://{gristhost}/api/orgs/{orgId}/workspaces"
15
+ WORKSPACE_CREATE = "https://{gristhost}/api/orgs/{orgId}/workspaces"
16
+
17
+ ### WORKSPACES
18
+ WORKSPACE_FIND = "https://{gristhost}/api/workspaces/{workspaceId}"
19
+ WORKSPACE_UPDATE = "https://{gristhost}/api/workspaces/{workspaceId}"
20
+ WORKSPACE_DELETE = "https://{gristhost}/api/workspaces/{workspaceId}"
21
+ # WORKSPACE ACCESS
22
+ WORKSPACE_ACCESS_ALL = "https://{gristhost}/api/workspaces/{orgId}/access"
23
+ WORKSPACE_ACCESS_UPDATE = "https://{gristhost}/api/workspaces/{orgId}/access"
24
+ # WORKSPACE DOCUMENTS
25
+ DOC_CREATE = "https://{gristhost}/api/workspaces/{workspaceId}/docs"
26
+
27
+ ### DOCUMENTS
28
+ DOC_FIND = "https://{gristhost}/api/docs/{docId}"
29
+ DOC_UPDATE = "https://{gristhost}/api/docs/{docId}"
30
+ DOC_DELETE = "https://{gristhost}/api/docs/{docId}"
31
+ DOC_MOVE = "https://{gristhost}/api/docs/{docId}/move"
32
+ # DOC ACCESS
33
+ DOC_ACCESS_ALL = "https://{gristhost}/api/docs/{docId}/access"
34
+ DOC_ACCESS_UPDATE = "https://{gristhost}/api/docs/{docId}/access"
35
+ # DOC ACCESS
36
+ DOC_DL_SQL = "https://{gristhost}/api/docs/{docId}/download"
37
+ DOC_DL_EXCEL = "https://{gristhost}/api/docs/{docId}/download/xlsx"
38
+ DOC_DL_CSV = "https://{gristhost}/api/docs/{docId}/download/csv"
39
+ DOC_DL_TABLE_SCHEMA = "https://{gristhost}/api/docs/{docId}/download/table-schema"
40
+ DOC_TRUNCATE_HISTORY = "https://{gristhost}/api/docs/{docId}/states/remove"
41
+ DOC_FORCE_RELOAD = "https://{gristhost}/api/docs/{docId}/force-reload"
42
+ DOC_CLEAR_QUEUE = "https://{gristhost}/api/docs/{docId}/webhooks/queue"
43
+
44
+ ### RECORDS
45
+ RECORD_ALL = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/records"
46
+ RECORD_CREATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/records"
47
+ RECORD_UPDATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/records"
48
+ RECORD_ADD_OR_UPDATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/records"
49
+
50
+ ### TABLES
51
+ TABLE_ALL = "https://{gristhost}/api/docs/{docId}/tables"
52
+ TABLE_CREATE = "https://{gristhost}/api/docs/{docId}/tables"
53
+ TABLE_UPDATE = "https://{gristhost}/api/docs/{docId}/tables"
54
+
55
+ ### COLUMNS
56
+ COLUMN_ALL = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/columns"
57
+ COLUMN_CREATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/columns"
58
+ COLUMN_UPDATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/columns"
59
+ COLUMN_ADD_OR_UPDATE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/columns"
60
+ COLUMN_DELETE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/columns/{colId}"
61
+
62
+ ### ROWS
63
+ ROW_DELETE = "https://{gristhost}/api/docs/{docId}/tables/{tableId}/data/delete"
64
+
65
+ ### ATTACHMENTS
66
+ ATTACHMENT_ALL = "https://{gristhost}/api/docs/{docId}/attachments"
67
+ ATTACHMENT_UPDATE = "https://{gristhost}/api/docs/{docId}/attachments"
68
+ ATTACHMENT_METADATA = "https://{gristhost}/api/docs/{docId}/attachments/{attachmentId}"
69
+ ATTACHMENT_DL_CONTENT = "https://{gristhost}/api/docs/{docId}/attachments/{attachmentId}/download"
70
+
71
+ ### WEBHOOKS
72
+ WEBHOOK_ALL = "https://{gristhost}/api/docs/{docId}/webhooks"
73
+ WEBHOOK_CREATE = "https://{gristhost}/api/docs/{docId}/webhooks"
74
+ WEBHOOK_UPDATE = "https://{gristhost}/api/docs/{docId}/webhooks/{webhookId}"
75
+ WEBHOOK_DELETE = "https://{gristhost}/api/docs/{docId}/webhooks/{webhookId}"
76
+
77
+ USER_DELETE = "https://{gristhost}/api/users/{userId}"
78
+ end
79
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grist
4
+ class Response
5
+ attr_reader :data, :error, :code, :type
6
+
7
+ def initialize(data: nil, error: nil, code: nil, type: nil)
8
+ @data = data
9
+ @error = error
10
+ @type = type
11
+ @code = code&.to_i
12
+ end
13
+
14
+ def success?
15
+ error.nil? && (@code >= 200 && @code < 400)
16
+ end
17
+
18
+ def error?
19
+ !error.nil? || !(@code >= 200 && @code < 400)
20
+ end
21
+
22
+ def not_found?
23
+ @code == 404
24
+ end
25
+
26
+ def print_error
27
+ err = "#{@type}: #{@error}"
28
+ err += " (code: #{@code})" if @code
29
+ err += "\n#{@type.help}" if @type.respond_to?(:help) && !@type.help.nil?
30
+ err
31
+ end
32
+
33
+ def log_error
34
+ return unless error?
35
+
36
+ Grist.logger.error("Grist API Error: #{@type} (code: #{@code})- #{@error}")
37
+ end
38
+ end
39
+ end
data/lib/grist/rest.rb ADDED
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grist
4
+ module Rest
5
+ def request(method, endpoint, params = {})
6
+ uri = URI("#{::Grist.base_api_url}#{endpoint}")
7
+ uri.query = URI.encode_www_form(params) if method == :get
8
+
9
+ http = ::Net::HTTP.new(uri.host, uri.port)
10
+ http.use_ssl = !::Grist.localhost?
11
+
12
+ request = ::Net::HTTP.const_get(method.capitalize).new(uri)
13
+ request["Authorization"] = ::Grist.token_auth
14
+ request["Content-Type"] = "application/json"
15
+ request.body = params.to_json unless method == :get
16
+
17
+ response = http.request(request)
18
+
19
+ raise InvalidApiKey, "Invalid API key" if response.is_a?(Net::HTTPUnauthorized)
20
+ raise NotFound, "Resource not found at : #{request.uri}" if response.is_a?(Net::HTTPNotFound)
21
+
22
+ data = response_body(response.body)
23
+
24
+ Grist::Response.new(data: data, code: response.code)
25
+ rescue Net::OpenTimeout, Net::ReadTimeout, SocketError => e
26
+ res = Grist::Response.new(code: response&.code, error: "Grist endpoint is unreachable at #{request.uri}",
27
+ type: e.class)
28
+ res.log_error
29
+ raise NetworkError, res.print_error
30
+ rescue APIError => e
31
+ res = Grist::Response.new(code: response&.code, error: e.message, type: e.class)
32
+ res.log_error
33
+ res
34
+ rescue StandardError, Grist::NotFound => e
35
+ res = Grist::Response.new(code: response&.code, error: e.message, type: e.class)
36
+ res.log_error
37
+ res
38
+ end
39
+
40
+ def path
41
+ self.class::PATH
42
+ end
43
+
44
+ def list(params = {})
45
+ request(:get, path, params)
46
+ end
47
+
48
+ def get(id)
49
+ request(:get, "#{path}/#{id}")
50
+ end
51
+
52
+ def create(data)
53
+ grist_res = request(:post, path, data)
54
+ puts "Creating #{path} with data: #{data}"
55
+ puts puts grist_res.inspect
56
+ return unless grist_res.success?
57
+
58
+ data.each_key do |key|
59
+ instance_variable_set("@#{key}", data[key])
60
+ end
61
+
62
+ self
63
+ end
64
+
65
+ def update(data)
66
+ id = instance_variable_get("@id")
67
+ grist_res = request(:patch, "#{path}/#{id}", data)
68
+ return unless grist_res.success?
69
+
70
+ data.each_key do |key|
71
+ instance_variable_set("@#{key}", data[key])
72
+ end
73
+
74
+ self
75
+ end
76
+
77
+ def delete
78
+ id = instance_variable_get("@id")
79
+ grist_res = request(:delete, "#{path}/#{id}")
80
+ return unless grist_res.success?
81
+
82
+ instance_variable_set("@deleted", true)
83
+
84
+ self
85
+ end
86
+
87
+ private
88
+
89
+ def response_body(str)
90
+ return {} if str.nil? || str.empty?
91
+
92
+ JSON.parse(str)
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grist
4
+ module Searchable
5
+ # Finds a record based on the given parameters.
6
+ # @param params [Hash] The parameters to search for
7
+ # @return [Array] The records that match the given parameters
8
+ def self.find_by(*params)
9
+ objs = all
10
+ objs.select do |obj|
11
+ params.all? do |key, value|
12
+ obj.instance_variable_get("@#{key}") == value
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end