diff --git a/.Rbuildignore b/.Rbuildignore new file mode 100644 index 0000000..88dbd38 --- /dev/null +++ b/.Rbuildignore @@ -0,0 +1,5 @@ +^.vscode +^LICENSE\.md$ +^nix +^shell.nix$ +^tmp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6661a2b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.vscode +tmp/ diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..2b72f01 --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,14 @@ +Package: rocketbase +Title: Unofficial PocketBase API Client +Version: 0.0.0.9000 +Authors@R: + person("Vehbi Sinan", "Tunalioglu", , "vst@vsthost.com", role = c("aut", "cre")) +Description: This package is an unofficial API client to the opensource headless content management service PocketBase. +License: MIT + file LICENSE +Encoding: UTF-8 +Roxygen: list(markdown = TRUE) +RoxygenNote: 7.2.1 +Imports: + R6, + crul, + jsonlite diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7494efa --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +YEAR: 2022 +COPYRIGHT HOLDER: rocketbase authors diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..70e01d9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2022 rocketbase authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..3bafe90 --- /dev/null +++ b/NAMESPACE @@ -0,0 +1,6 @@ +# Generated by roxygen2: do not edit by hand + +export(RocketBase) +importFrom(R6,R6Class) +importFrom(crul,HttpClient) +importFrom(jsonlite,fromJSON) diff --git a/R/base.R b/R/base.R new file mode 100644 index 0000000..d05c5fe --- /dev/null +++ b/R/base.R @@ -0,0 +1,107 @@ +#' @title PocketBase API Client +#' +#' @description Instances of this class can be used for conveniently issuing +#' HTTP requests to remote PocketBase API instances. +#' +#' Note that this client only works with admin users at the moment. +#' +#' @importFrom crul HttpClient +#' @importFrom jsonlite fromJSON +#' @importFrom R6 R6Class +#' @export +RocketBase <- R6::R6Class("RocketBase", ## nolint + public = list( + #' @field url Base URL of the remote PocketBase API instance. + url = NULL, + + #' @field bare Bare HTTP client for the remote PocketBase API instance. + #' + #' This is a plain vanilla `crul::HttpClient` instance that is ready to + #' issue requests to remote PocketBase API instance. Indeed, this + #' instance should be sufficient for most API communication with + #' PocketBase API instances. + bare = NULL, + + #' @description Creates a PocketBase API client instance. + #' + #' @param url Base URL of the remote PocketBase API instance. + #' @param identity Identity credential for authentication. + #' @param password Password credential for authentication. + #' + #' @return A new `RocketBase` object. + #' @examples + #' \dontrun{ + #' client <- rocketbase::RocketBase$new( + #' url = "https://httpbin.org", + #' identity = "hebele", + #' password = "hubele" + #' ) + #' } + initialize = function(url, identity, password) { + self$url <- url + private$identity <- identity + private$password <- password + private$setup() + }, + + #' @description Prints rudimentary information about the remote PocketBase API instance. + info = function() { + cat(sprintf("PocketBase Instance URL: %s\n", self$url)) + }, + + #' @description Provides the print function for `RocketBase` object. + print = function() { + print(sprintf("", self$url)) + } + ), + private = list( + ## Identity credential for the remote PocketBase API instance. + identity = NULL, + + ## Password credential for the remote PocketBase API instance. + password = NULL, + + ## Token credential for the remote PocketBase API instance. + token = NULL, + + ## Setups this instance. + setup = function() { + ## Attempt to authenticate and get the authentication token: + private$token <- private$authenticate() + + ## Build the bare HTTP client: + self$bare <- crul::HttpClient$new( + url = self$url, + headers = list( + Authorization=sprintf("%s", private$token), + "User-Agent"=private$useragent() + ) + ) + }, + + ## Attempts to authenticate and get a token. + authenticate = function() { + ## Build the HTTP client: + client <- crul::HttpClient$new(url = self$url) + + ## Issue the authentication request and get a response: + response <- client$post("/api/admins/auth-with-password", body=list(identity=private$identity, password=private$password)) + + ## Check if response status is 200. If not, raise error as it implies that authentication has failed. + if (response$status_code != 200) { + stop("Authentication failed.") + } + + ## Parse the content of the response: + content <- jsonlite::fromJSON(response$parse(encoding="UTF-8")) + + ## Return the authentication token: + content$token + }, + + ## Builds the user-agent string. + useragent = function() { + sprintf( "rocketbase/%s (%s; on:%s)", utils::packageVersion("rocketbase"), Sys.info()["sysname"], Sys.info()["nodename"]) + } + ) +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..224ecf6 --- /dev/null +++ b/README.md @@ -0,0 +1,111 @@ +# rocketbase - Unofficial PocketBase API Client for R + +![GitHub release (latest by date)](https://img.shields.io/github/v/release/telostat/rocketbase) +![github last commit](https://img.shields.io/github/last-commit/telostat/rocketbase) +![GitHub contributors](https://img.shields.io/github/contributors/telostat/rocketbase) + +`rocketbase` is an unofficial [PocketBase](https://pocketbase.io/) API client +for R. + +## Installation + +`rocketbase` is currently not on [CRAN](https://cran.r-project.org/). The +easiest way to install it is using [devtools](https://devtools.r-lib.org/). + +For the latest development snapshot: + +```R +devtools::install_github("telostat/rocketbase", upgrade="ask") +``` + +For the latest version (`X.Y.Z`, following [semantic +versioning](https://semver.org/)): + +```R +devtools::install_github("telostat/rocketbase", ref="X.Y.Z", upgrade="ask") +``` + +## Development + +Enter the Nix shell and launch PocketBase: + +```sh +nix-shell +pocketbase-serve +``` + +Create an admin user account on PocketBase. Now, on another console session, +enter Nix shell: + +```sh +nix-shell +``` + +Launch R: + +```sh +R +``` + +Here is a sample session: + +```R +devtools::load_all(".") +rb <- rocketbase::RocketBase$new("http://localhost:8090", identity = "hebele@hubele.com", password = "hebelehubele") +response <- rb$bare$get("/api/collections/users/records") +stopifnot(response$status_code == 200) +my_data <- jsonlite::fromJSON(response$parse(encoding = "UTF-8")) +print(my_data) + +table <- list( + name = "observations", + type = "base", + system = FALSE, + schema = list( + list( + "name" = "key", + "type" = "text", + "system" = FALSE, + "required" = TRUE, + "unique" = TRUE, + "nullable" = FALSE + ), + list( + "name" = "value", + "type" = "text", + "system" = FALSE, + "required" = FALSE, + "unique" = FALSE, + "nullable" = TRUE + ) + ) +) +response <- rb$bare$post("/api/collections", encode = "json", body=table) +stopifnot(response$status_code == 200) + +response <- rb$bare$get("/api/collections/observations/records") +stopifnot(response$status_code == 200) +my_data <- jsonlite::fromJSON(response$parse(encoding = "UTF-8")) +print(my_data) + +response <- rb$bare$post("/api/collections/observations/records", encode = "json", body=list( + key = "key1", + value = "value1" +)) +stopifnot(response$status_code == 200) + +response <- rb$bare$post("/api/collections/observations/records", encode = "json", body=list( + key = "key2", + value = "value2" +)) +stopifnot(response$status_code == 200) + +response <- rb$bare$get("/api/collections/observations/records") +stopifnot(response$status_code == 200) +my_data <- jsonlite::fromJSON(response$parse(encoding = "UTF-8")) +print(my_data) +``` + +## License + +This work is licensed under MIT license. See [LICENSE](./LICENSE.md). diff --git a/man/RocketBase.Rd b/man/RocketBase.Rd new file mode 100644 index 0000000..c524aad --- /dev/null +++ b/man/RocketBase.Rd @@ -0,0 +1,124 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/base.R +\name{RocketBase} +\alias{RocketBase} +\title{PocketBase API Client} +\description{ +Instances of this class can be used for conveniently issuing +HTTP requests to remote PocketBase API instances. + +Note that this client only works with admin users at the moment. +} +\examples{ + +## ------------------------------------------------ +## Method `RocketBase$new` +## ------------------------------------------------ + +\dontrun{ +client <- rocketbase::RocketBase$new( + url = "https://httpbin.org", + identity = "hebele", + password = "hubele" +) +} +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{url}}{Base URL of the remote PocketBase API instance.} + +\item{\code{bare}}{Bare HTTP client for the remote PocketBase API instance. + +This is a plain vanilla \code{crul::HttpClient} instance that is ready to +issue requests to remote PocketBase API instance. Indeed, this +instance should be sufficient for most API communication with +PocketBase API instances.} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-RocketBase-new}{\code{RocketBase$new()}} +\item \href{#method-RocketBase-info}{\code{RocketBase$info()}} +\item \href{#method-RocketBase-print}{\code{RocketBase$print()}} +\item \href{#method-RocketBase-clone}{\code{RocketBase$clone()}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-RocketBase-new}{}}} +\subsection{Method \code{new()}}{ +Creates a PocketBase API client instance. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{RocketBase$new(url, identity, password)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{url}}{Base URL of the remote PocketBase API instance.} + +\item{\code{identity}}{Identity credential for authentication.} + +\item{\code{password}}{Password credential for authentication.} +} +\if{html}{\out{
}} +} +\subsection{Returns}{ +A new \code{RocketBase} object. +} +\subsection{Examples}{ +\if{html}{\out{
}} +\preformatted{\dontrun{ +client <- rocketbase::RocketBase$new( + url = "https://httpbin.org", + identity = "hebele", + password = "hubele" +) +} +} +\if{html}{\out{
}} + +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-RocketBase-info}{}}} +\subsection{Method \code{info()}}{ +Prints rudimentary information about the remote PocketBase API instance. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{RocketBase$info()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-RocketBase-print}{}}} +\subsection{Method \code{print()}}{ +Provides the print function for \code{RocketBase} object. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{RocketBase$print()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-RocketBase-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{RocketBase$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/nix/sources.json b/nix/sources.json new file mode 100644 index 0000000..d24b697 --- /dev/null +++ b/nix/sources.json @@ -0,0 +1,14 @@ +{ + "nixpkgs": { + "branch": "nixpkgs-unstable", + "description": "Nix Packages collection", + "homepage": "", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "227de2b3bbec142f912c09d5e8a1b4e778aa54fb", + "sha256": "04is77q4msyqi51q8zxialyl378hzv47ldml5hnycg42zvnzpi24", + "type": "tarball", + "url": "https://github.com/NixOS/nixpkgs/archive/227de2b3bbec142f912c09d5e8a1b4e778aa54fb.tar.gz", + "url_template": "https://github.com///archive/.tar.gz" + } +} diff --git a/nix/sources.nix b/nix/sources.nix new file mode 100644 index 0000000..9a01c8a --- /dev/null +++ b/nix/sources.nix @@ -0,0 +1,194 @@ +# This file has been generated by Niv. + +let + + # + # The fetchers. fetch_ fetches specs of type . + # + + fetch_file = pkgs: name: spec: + let + name' = sanitizeName name + "-src"; + in + if spec.builtin or true then + builtins_fetchurl { inherit (spec) url sha256; name = name'; } + else + pkgs.fetchurl { inherit (spec) url sha256; name = name'; }; + + fetch_tarball = pkgs: name: spec: + let + name' = sanitizeName name + "-src"; + in + if spec.builtin or true then + builtins_fetchTarball { name = name'; inherit (spec) url sha256; } + else + pkgs.fetchzip { name = name'; inherit (spec) url sha256; }; + + fetch_git = name: spec: + let + ref = + if spec ? ref then spec.ref else + if spec ? branch then "refs/heads/${spec.branch}" else + if spec ? tag then "refs/tags/${spec.tag}" else + abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!"; + submodules = if spec ? submodules then spec.submodules else false; + submoduleArg = + let + nixSupportsSubmodules = builtins.compareVersions builtins.nixVersion "2.4" >= 0; + emptyArgWithWarning = + if submodules == true + then + builtins.trace + ( + "The niv input \"${name}\" uses submodules " + + "but your nix's (${builtins.nixVersion}) builtins.fetchGit " + + "does not support them" + ) + {} + else {}; + in + if nixSupportsSubmodules + then { inherit submodules; } + else emptyArgWithWarning; + in + builtins.fetchGit + ({ url = spec.repo; inherit (spec) rev; inherit ref; } // submoduleArg); + + fetch_local = spec: spec.path; + + fetch_builtin-tarball = name: throw + ''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`. + $ niv modify ${name} -a type=tarball -a builtin=true''; + + fetch_builtin-url = name: throw + ''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`. + $ niv modify ${name} -a type=file -a builtin=true''; + + # + # Various helpers + # + + # https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695 + sanitizeName = name: + ( + concatMapStrings (s: if builtins.isList s then "-" else s) + ( + builtins.split "[^[:alnum:]+._?=-]+" + ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name) + ) + ); + + # The set of packages used when specs are fetched using non-builtins. + mkPkgs = sources: system: + let + sourcesNixpkgs = + import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; }; + hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath; + hasThisAsNixpkgsPath = == ./.; + in + if builtins.hasAttr "nixpkgs" sources + then sourcesNixpkgs + else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then + import {} + else + abort + '' + Please specify either (through -I or NIX_PATH=nixpkgs=...) or + add a package called "nixpkgs" to your sources.json. + ''; + + # The actual fetching function. + fetch = pkgs: name: spec: + + if ! builtins.hasAttr "type" spec then + abort "ERROR: niv spec ${name} does not have a 'type' attribute" + else if spec.type == "file" then fetch_file pkgs name spec + else if spec.type == "tarball" then fetch_tarball pkgs name spec + else if spec.type == "git" then fetch_git name spec + else if spec.type == "local" then fetch_local spec + else if spec.type == "builtin-tarball" then fetch_builtin-tarball name + else if spec.type == "builtin-url" then fetch_builtin-url name + else + abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}"; + + # If the environment variable NIV_OVERRIDE_${name} is set, then use + # the path directly as opposed to the fetched source. + replace = name: drv: + let + saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name; + ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}"; + in + if ersatz == "" then drv else + # this turns the string into an actual Nix path (for both absolute and + # relative paths) + if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}"; + + # Ports of functions for older nix versions + + # a Nix version of mapAttrs if the built-in doesn't exist + mapAttrs = builtins.mapAttrs or ( + f: set: with builtins; + listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set)) + ); + + # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295 + range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1); + + # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257 + stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1)); + + # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269 + stringAsChars = f: s: concatStrings (map f (stringToCharacters s)); + concatMapStrings = f: list: concatStrings (map f list); + concatStrings = builtins.concatStringsSep ""; + + # https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331 + optionalAttrs = cond: as: if cond then as else {}; + + # fetchTarball version that is compatible between all the versions of Nix + builtins_fetchTarball = { url, name ? null, sha256 }@attrs: + let + inherit (builtins) lessThan nixVersion fetchTarball; + in + if lessThan nixVersion "1.12" then + fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; })) + else + fetchTarball attrs; + + # fetchurl version that is compatible between all the versions of Nix + builtins_fetchurl = { url, name ? null, sha256 }@attrs: + let + inherit (builtins) lessThan nixVersion fetchurl; + in + if lessThan nixVersion "1.12" then + fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; })) + else + fetchurl attrs; + + # Create the final "sources" from the config + mkSources = config: + mapAttrs ( + name: spec: + if builtins.hasAttr "outPath" spec + then abort + "The values in sources.json should not have an 'outPath' attribute" + else + spec // { outPath = replace name (fetch config.pkgs name spec); } + ) config.sources; + + # The "config" used by the fetchers + mkConfig = + { sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null + , sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile) + , system ? builtins.currentSystem + , pkgs ? mkPkgs sources system + }: rec { + # The sources, i.e. the attribute set of spec name to spec + inherit sources; + + # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers + inherit pkgs; + }; + +in +mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); } diff --git a/shell.nix b/shell.nix new file mode 100644 index 0000000..86f16d5 --- /dev/null +++ b/shell.nix @@ -0,0 +1,31 @@ +let + sources = import ./nix/sources.nix { }; + pkgs = import sources.nixpkgs { }; + + devDependencies = [ + pkgs.rPackages.devtools + pkgs.rPackages.roxygen2 + ]; + + libDependencies = [ + pkgs.rPackages.crul + pkgs.rPackages.jsonlite + pkgs.rPackages.R6 + ]; + + thisR = pkgs.rWrapper.override { + packages = devDependencies ++ libDependencies; + }; +in +pkgs.mkShell { + buildInputs = [ + thisR + pkgs.pocketbase + ]; + + shellHook = '' + export ROCKETBASE_DIR="./tmp/pg_data" + alias pocketbase-reset="find ./tmp/pg_data -type f -delete" + alias pocketbase-serve="pocketbase serve --dir ./tmp/pg_data" + ''; +}