mirror of
https://github.com/jlengrand/postgrest-kt.git
synced 2026-03-10 08:41:18 +00:00
Initial commit
This commit is contained in:
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
# Ignore Gradle project-specific cache directory
|
||||
.gradle
|
||||
|
||||
# Ignore Gradle build output directory
|
||||
build
|
||||
|
||||
.idea
|
||||
5
README.md
Normal file
5
README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
= Kotlin Client for PostgREST
|
||||
|
||||
Kotlin JVMclient for [PostgREST](https://postgrest.org/)
|
||||
|
||||
WIP
|
||||
132
build.gradle
Normal file
132
build.gradle
Normal file
@@ -0,0 +1,132 @@
|
||||
plugins {
|
||||
// Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
|
||||
id 'org.jetbrains.kotlin.jvm' version '1.4.21'
|
||||
|
||||
// Apply the java-library plugin for API and implementation separation.
|
||||
id 'java-library'
|
||||
|
||||
id "com.github.ben-manes.versions" version "0.36.0"
|
||||
|
||||
id "maven-publish"
|
||||
|
||||
id "com.jfrog.bintray" version "1.8.5"
|
||||
}
|
||||
|
||||
String currentVersion = '0.2.0'
|
||||
|
||||
group = 'io.supabase'
|
||||
version = currentVersion
|
||||
|
||||
repositories {
|
||||
jcenter()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
compile "org.apache.httpcomponents.client5:httpclient5:5.0.3"
|
||||
|
||||
// Align versions of all Kotlin components
|
||||
implementation platform('org.jetbrains.kotlin:kotlin-bom')
|
||||
|
||||
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
|
||||
|
||||
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1"
|
||||
implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.1"
|
||||
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.7.0'
|
||||
testImplementation "io.mockk:mockk:1.10.5"
|
||||
testImplementation 'com.willowtreeapps.assertk:assertk-jvm:0.23'
|
||||
testCompile "com.github.tomakehurst:wiremock-jre8:2.27.2"
|
||||
|
||||
}
|
||||
|
||||
compileKotlin {
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
}
|
||||
|
||||
compileTestKotlin {
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
task sourcesJar(type: Jar) {
|
||||
from sourceSets.main.allSource
|
||||
}
|
||||
|
||||
task javadocJar(type: Jar, dependsOn: project.javadoc) {
|
||||
from javadoc.destinationDir
|
||||
}
|
||||
|
||||
def pomConfig = {
|
||||
licenses {
|
||||
license {
|
||||
name "The MIT License"
|
||||
url "https://opensource.org/licenses/MIT"
|
||||
distribution "repo"
|
||||
}
|
||||
}
|
||||
developers {
|
||||
developer {
|
||||
id "kevcodez"
|
||||
name "Kevin Grüneberg"
|
||||
email "k.grueneberg1994@gmail.com"
|
||||
}
|
||||
}
|
||||
|
||||
scm {
|
||||
url "https://github.com/supabase/postgrest-kt"
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
mavenPublication(MavenPublication) {
|
||||
from components.java
|
||||
|
||||
artifact sourcesJar {
|
||||
classifier "sources"
|
||||
}
|
||||
artifact javadocJar {
|
||||
classifier "javadoc"
|
||||
}
|
||||
|
||||
groupId 'io.supabase'
|
||||
artifactId 'postgrest-kt'
|
||||
pom.withXml {
|
||||
def root = asNode()
|
||||
root.appendNode('description', 'Kotlin JVM client for PostgREST API.')
|
||||
root.appendNode('name', 'PostgREST Kotlin')
|
||||
root.appendNode('url', 'https://github.com/supabase/postgrest-kt')
|
||||
root.children().last() + pomConfig
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bintray {
|
||||
user = System.getenv("bintray_user") ?: findProperty("bintray_user")
|
||||
key = System.getenv("bintray_key") ?: findProperty("bintray_key")
|
||||
publications = ['mavenPublication']
|
||||
publish = true
|
||||
|
||||
pkg {
|
||||
repo = 'supabase'
|
||||
name = 'postgrest-kt'
|
||||
userOrg = 'supabase'
|
||||
licenses = ['MIT']
|
||||
vcsUrl = 'https://github.com/supabase/postgrest-kt.git'
|
||||
version {
|
||||
name = currentVersion
|
||||
desc = currentVersion
|
||||
released = new Date()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
185
gradlew
vendored
Normal file
185
gradlew
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
89
gradlew.bat
vendored
Normal file
89
gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'postgrest-kt'
|
||||
23
src/main/kotlin/io/supabase/postgrest/PostgrestClient.kt
Normal file
23
src/main/kotlin/io/supabase/postgrest/PostgrestClient.kt
Normal file
@@ -0,0 +1,23 @@
|
||||
package io.supabase.postgrest
|
||||
|
||||
import io.supabase.postgrest.builder.PostgrestQueryBuilder
|
||||
import io.supabase.postgrest.http.PostgrestHttpClient
|
||||
import java.net.URI
|
||||
|
||||
open class PostgrestClient(
|
||||
private val uri: URI,
|
||||
private val postgrestHttpClient: PostgrestHttpClient,
|
||||
private val defaultHeaders: Map<String, String> = emptyMap()
|
||||
) {
|
||||
|
||||
/**
|
||||
* Perform a table operation.
|
||||
*
|
||||
* @param[table] The table name to operate on.
|
||||
*/
|
||||
fun <T : Any> from(table: String): PostgrestQueryBuilder<T> {
|
||||
val uri = URI("$uri/$table")
|
||||
return PostgrestQueryBuilder(uri, postgrestHttpClient, defaultHeaders)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.supabase.postgrest
|
||||
|
||||
import io.supabase.postgrest.http.PostgrestHttpClient
|
||||
import io.supabase.postgrest.http.PostgrestHttpClientApache
|
||||
import io.supabase.postgrest.json.PostgrestJsonConverter
|
||||
import io.supabase.postgrest.json.PostgrestJsonConverterJackson
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients
|
||||
import java.net.URI
|
||||
|
||||
val jsonConverter = PostgrestJsonConverterJackson()
|
||||
|
||||
/**
|
||||
* The default client uses Apache HTTP client 5.x and Jackson FasterXML for DTO conversion.
|
||||
*
|
||||
* If you want to customize, implement [PostgrestHttpClient] and [PostgrestJsonConverter].
|
||||
*/
|
||||
class PostgrestDefaultClient(
|
||||
uri: URI,
|
||||
defaultHeaders: Map<String, String> = emptyMap()
|
||||
) : PostgrestClient(
|
||||
postgrestHttpClient = PostgrestHttpClientApache(
|
||||
httpClient = HttpClients.createDefault(),
|
||||
postgrestJsonConverter = jsonConverter
|
||||
),
|
||||
defaultHeaders = defaultHeaders,
|
||||
uri = uri
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.supabase.postgrest.builder
|
||||
|
||||
import io.supabase.postgrest.http.HttpResponse
|
||||
import io.supabase.postgrest.http.PostgrestHttpClient
|
||||
import org.apache.hc.core5.http.Method
|
||||
import java.net.URI
|
||||
|
||||
open class PostgrestBuilder<T : Any> {
|
||||
|
||||
private val postgrestHttpClient: PostgrestHttpClient
|
||||
private val url: URI
|
||||
|
||||
private var headers: MutableMap<String, String> = mutableMapOf()
|
||||
private var method: Method? = null
|
||||
private var schema: String? = null
|
||||
private var body: Any? = null
|
||||
private var searchParams: MutableMap<String, String> = mutableMapOf()
|
||||
|
||||
constructor(builder: PostgrestBuilder<T>) {
|
||||
this.headers = builder.headers
|
||||
this.method = builder.method
|
||||
this.postgrestHttpClient = builder.postgrestHttpClient
|
||||
this.url = builder.url
|
||||
this.schema = builder.schema
|
||||
this.body = builder.body
|
||||
}
|
||||
|
||||
constructor(url: URI, postgrestHttpClient: PostgrestHttpClient, defaultHeaders: Map<String, String>) {
|
||||
this.url = url
|
||||
this.postgrestHttpClient = postgrestHttpClient
|
||||
|
||||
defaultHeaders.forEach { (name, value) -> setHeader(name, value) }
|
||||
}
|
||||
|
||||
protected fun setHeader(name: String, value: String) {
|
||||
this.headers[name] = value
|
||||
}
|
||||
|
||||
protected fun setSearchParam(name: String, value: String) {
|
||||
this.searchParams[name] = value
|
||||
}
|
||||
|
||||
protected fun setMethod(method: Method) {
|
||||
this.method = method
|
||||
}
|
||||
|
||||
protected fun setBody(body: Any?) {
|
||||
this.body = body
|
||||
}
|
||||
|
||||
fun execute(): HttpResponse {
|
||||
checkNotNull(method) { "Method cannot be null" }
|
||||
|
||||
return postgrestHttpClient.execute(
|
||||
url = url,
|
||||
method = method!!,
|
||||
headers = headers,
|
||||
body = body,
|
||||
schema = schema
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package io.supabase.postgrest.builder
|
||||
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
class PostgrestFilterBuilder<T : Any>(builder: PostgrestBuilder<T>) : PostgrestTransformBuilder<T>(builder) {
|
||||
|
||||
/**
|
||||
* Finds all rows which doesn't satisfy the filter.
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param operator The operator to filter with.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun not(column: KProperty<T>, operator: FilterOperator, value: Any): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "not.${operator.identifier}.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows satisfying at least one of the filters.
|
||||
*
|
||||
* @param filters The filters to use, separated by commas.
|
||||
*/
|
||||
fun or(filters: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam("or", "(${filters})")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" exactly matches the
|
||||
* specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun eq(column: KProperty<T>, value: Any): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "eq.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" doesn't match the
|
||||
* specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun neq(column: KProperty<T>, value: T): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "neq.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" is greater than the
|
||||
* specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun gt(column: KProperty<T>, value: T): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "gt.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" is greater than or
|
||||
* equal to the specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun gte(column: KProperty<T>, value: T): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "gte.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" is less than the
|
||||
* specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun lt(column: KProperty<T>, value: T): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "lt.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" is less than or equal
|
||||
* to the specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun lte(column: KProperty<T>, value: T): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "lte.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value in the stated "column" matches the supplied
|
||||
* "pattern" (case sensitive).
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param pattern The pattern to filter with.
|
||||
*/
|
||||
fun like(column: KProperty<T>, pattern: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "like.${pattern}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value in the stated "column" matches the supplied
|
||||
* "pattern" (case insensitive).
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param pattern The pattern to filter with.
|
||||
*/
|
||||
fun ilike(column: KProperty<T>, pattern: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "ilike.${pattern}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* A check for exact equality (null, true, false), finds all rows whose
|
||||
* value on the stated "column" exactly match the specified "value".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun `is`(column: KProperty<T>, value: Boolean?): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "is.${value}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose value on the stated "column" is found on the
|
||||
* specified "values".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param values The values to filter with.
|
||||
*/
|
||||
fun `in`(column: KProperty<T>, values: List<Any>): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "in.(${cleanFilterArray(values)})")
|
||||
return this
|
||||
}
|
||||
|
||||
private fun cleanFilterArray(values: List<Any>): String {
|
||||
return values.joinToString(",") { s -> """"$s"""" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose range value on the stated "column" is strictly to the
|
||||
* left of the specified "range".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param range The range to filter with.
|
||||
*/
|
||||
fun sl(column: KProperty<T>, range: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "sl.${range}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose range value on the stated "column" is strictly to
|
||||
* the right of the specified "range".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param range The range to filter with.
|
||||
*/
|
||||
fun sr(column: KProperty<T>, range: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "sr.${range}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose range value on the stated "column" does not extend
|
||||
* to the left of the specified "range".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param range The range to filter with.
|
||||
*/
|
||||
fun nxl(column: KProperty<T>, range: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "nxl.${range}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose range value on the stated "column" does not extend
|
||||
* to the right of the specified "range".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param range The range to filter with.
|
||||
*/
|
||||
fun nxr(column: KProperty<T>, range: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "nxr.${range}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose range value on the stated "column" is adjacent to
|
||||
* the specified "range".
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param range The range to filter with.
|
||||
*/
|
||||
fun adj(column: KProperty<T>, range: String): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "adj.${range}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose tsvector value on the stated "column" matches
|
||||
* to_tsquery("query").
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param query The Postgres tsquery String to filter with.
|
||||
* @param config The text search configuration to use.
|
||||
*/
|
||||
fun fts(column: KProperty<T>, query: String, config: String? = null): PostgrestFilterBuilder<T> {
|
||||
val configPart = if (config === null) "" else "(${config})"
|
||||
setSearchParam(column.name, "fts${configPart}.${query}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose tsvector value on the stated "column" matches
|
||||
* plainto_tsquery("query").
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param query The Postgres tsquery String to filter with.
|
||||
* @param config The text search configuration to use.
|
||||
*/
|
||||
fun plfts(column: KProperty<T>, query: String, config: String? = null): PostgrestFilterBuilder<T> {
|
||||
val configPart = if (config === null) "" else "(${config})"
|
||||
setSearchParam(column.name, "plfts${configPart}.${query}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose tsvector value on the stated "column" matches
|
||||
* phraseto_tsquery("query").
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param query The Postgres tsquery String to filter with.
|
||||
* @param config The text search configuration to use.
|
||||
*/
|
||||
fun phfts(column: KProperty<T>, query: String, config: String? = null): PostgrestFilterBuilder<T> {
|
||||
val configPart = if (config === null) "" else "(${config})"
|
||||
setSearchParam(column.name, "phfts${configPart}.${query}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose tsvector value on the stated "column" matches
|
||||
* websearch_to_tsquery("query").
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param query The Postgres tsquery String to filter with.
|
||||
* @param config The text search configuration to use.
|
||||
*/
|
||||
fun wfts(column: KProperty<T>, query: String, config: String? = null): PostgrestFilterBuilder<T> {
|
||||
val configPart = if (config === null) "" else "(${config})"
|
||||
setSearchParam(column.name, "wfts${configPart}.${query}")
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all rows whose "column" satisfies the filter.
|
||||
*
|
||||
* @param column The column to filter on.
|
||||
* @param operator The operator to filter with.
|
||||
* @param value The value to filter with.
|
||||
*/
|
||||
fun filter(column: KProperty<T>, operator: FilterOperator, value: Any): PostgrestFilterBuilder<T> {
|
||||
setSearchParam(column.name, "${operator.identifier}.${value}")
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
enum class FilterOperator(val identifier: String) {
|
||||
EQ("eq"),
|
||||
NEQ("neq"),
|
||||
GT("gt"),
|
||||
GTE("gte"),
|
||||
LT("lt"),
|
||||
LTE("lte"),
|
||||
LIKE("like"),
|
||||
ILIKE("ilike"),
|
||||
IS("is"),
|
||||
IN("in"),
|
||||
CS("cs"),
|
||||
CD("cd"),
|
||||
SL("sl"),
|
||||
SR("sr"),
|
||||
NXL("nxl"),
|
||||
NXR("nxr"),
|
||||
ADJ("adj"),
|
||||
OV("ov"),
|
||||
FTS("fts"),
|
||||
PLFTS("plfts"),
|
||||
PHFTS("phfts"),
|
||||
WFTS("wfts"),
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package io.supabase.postgrest.builder
|
||||
|
||||
import io.supabase.postgrest.http.PostgrestHttpClient
|
||||
import org.apache.hc.core5.http.Method
|
||||
import java.net.URI
|
||||
|
||||
class PostgrestQueryBuilder<T : Any>(url: URI, postgrestHttpClient: PostgrestHttpClient, defaultHeaders: Map<String, String>) : PostgrestBuilder<T>(url, postgrestHttpClient, defaultHeaders) {
|
||||
|
||||
/**
|
||||
* Performs vertical filtering with SELECT.
|
||||
*
|
||||
* @param[columns] The columns to retrieve, separated by commas.
|
||||
* @param[head] When set to true, select will void data.
|
||||
* @param[count] Count algorithm to use to count rows in a table.
|
||||
*/
|
||||
fun select(
|
||||
columns: String = "*",
|
||||
head: Boolean = false,
|
||||
count: Count? = null
|
||||
): PostgrestFilterBuilder<T> {
|
||||
setMethod(Method.GET)
|
||||
|
||||
val cleanedColumns = cleanColumns(columns)
|
||||
|
||||
setSearchParam("select", cleanedColumns)
|
||||
|
||||
if (count != null) {
|
||||
setHeader("Prefer", "count=${count.identifier}")
|
||||
}
|
||||
|
||||
if (head) {
|
||||
setMethod(Method.HEAD)
|
||||
}
|
||||
|
||||
return PostgrestFilterBuilder(this)
|
||||
}
|
||||
|
||||
fun insert(value: List<T>, upsert: Boolean = false, onConflict: String? = null, returning: Returning = Returning.REPRESENTATION, count: Count?): PostgrestFilterBuilder<T> {
|
||||
setMethod(Method.POST)
|
||||
|
||||
val preferHeaders = mutableListOf<String>("return=${returning.identifier}")
|
||||
if (upsert) preferHeaders.add("resolution=merge-duplicates")
|
||||
|
||||
if (upsert && onConflict != null) setSearchParam("on_conflict", onConflict)
|
||||
setBody(value)
|
||||
|
||||
if (count != null) {
|
||||
preferHeaders.add("count=${count}")
|
||||
}
|
||||
|
||||
setHeader("Prefer", preferHeaders.joinToString(","))
|
||||
|
||||
return PostgrestFilterBuilder(this)
|
||||
}
|
||||
|
||||
fun insert(value: T, upsert: Boolean = false, onConflict: String? = null, returning: Returning = Returning.REPRESENTATION, count: Count?): PostgrestFilterBuilder<T> {
|
||||
return insert(listOf(value), upsert, onConflict, returning, count)
|
||||
}
|
||||
|
||||
fun update(value: Any, returning: Returning = Returning.REPRESENTATION, count: Count?): PostgrestFilterBuilder<T> {
|
||||
setMethod(Method.PATCH)
|
||||
val prefersHeaders = mutableListOf("return=${returning.identifier}")
|
||||
setBody(value)
|
||||
if (count != null) {
|
||||
prefersHeaders.add("count=${count}")
|
||||
}
|
||||
setHeader("Prefer", prefersHeaders.joinToString(","))
|
||||
|
||||
return PostgrestFilterBuilder(this)
|
||||
}
|
||||
|
||||
fun delete(returning: Returning = Returning.REPRESENTATION, count: Count?): PostgrestFilterBuilder<T> {
|
||||
setMethod(Method.DELETE)
|
||||
|
||||
val prefersHeaders = mutableListOf("return=${returning.identifier}")
|
||||
if (count != null) {
|
||||
prefersHeaders.add("count=${count}")
|
||||
}
|
||||
setHeader("Prefer", prefersHeaders.joinToString(","))
|
||||
|
||||
return PostgrestFilterBuilder(this)
|
||||
}
|
||||
}
|
||||
|
||||
enum class Count(val identifier: String) {
|
||||
EXACT("exact"),
|
||||
PLANNED("planned"),
|
||||
ESTIMATED("estimated")
|
||||
}
|
||||
|
||||
enum class Returning(val identifier: String) {
|
||||
MINIMAL("minimal"),
|
||||
REPRESENTATION("representation")
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package io.supabase.postgrest.builder
|
||||
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
open class PostgrestTransformBuilder<T : Any>(builder: PostgrestBuilder<T>) : PostgrestBuilder<T>(builder) {
|
||||
|
||||
fun select(columns: String = "*"): PostgrestTransformBuilder<T> {
|
||||
val cleanedColumns = cleanColumns(columns)
|
||||
setSearchParam("select", cleanedColumns)
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
fun order(column: KProperty<T>, ascending: Boolean = true, nullsFirst: Boolean = false, foreignTable: String? = null): PostgrestTransformBuilder<T> {
|
||||
val key = if (foreignTable == null) "order" else """"$foreignTable".order"""
|
||||
setSearchParam(
|
||||
key,
|
||||
"${column}.${if (ascending) "asc" else "desc"}.${if (nullsFirst) "nullsfirst" else "nullslast"}"
|
||||
)
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
fun limit(count: Long, foreignTable: String? = null): PostgrestTransformBuilder<T> {
|
||||
val key = if (foreignTable == null) "limit" else """"$foreignTable".limit"""
|
||||
setSearchParam(key, count.toString())
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
fun range(from: Long, to: Long, foreignTable: String? = null): PostgrestTransformBuilder<T> {
|
||||
val keyOffset = if (foreignTable == null) "offset" else """"$foreignTable".offset"""
|
||||
val keyLimit = if (foreignTable == null) "limit" else """"$foreignTable".limit"""
|
||||
|
||||
setSearchParam(keyOffset, from.toString())
|
||||
// Range is inclusive, so add 1
|
||||
setSearchParam(keyLimit, (to - from + 1).toString())
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
fun single(): PostgrestTransformBuilder<T> {
|
||||
setHeader(org.apache.hc.core5.http.HttpHeaders.ACCEPT, "application/vnd.pgrst.object+json")
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
}
|
||||
21
src/main/kotlin/io/supabase/postgrest/builder/Util.kt
Normal file
21
src/main/kotlin/io/supabase/postgrest/builder/Util.kt
Normal file
@@ -0,0 +1,21 @@
|
||||
package io.supabase.postgrest.builder
|
||||
|
||||
/**
|
||||
* Remove whitespaces except when quoted
|
||||
*/
|
||||
fun cleanColumns(columns: String): String {
|
||||
var quoted = false
|
||||
|
||||
return columns
|
||||
.split("")
|
||||
.map { character ->
|
||||
if (character.matches(Regex("\\s")) && !quoted) {
|
||||
return@map ""
|
||||
}
|
||||
if (character == "\"") {
|
||||
quoted = !quoted
|
||||
}
|
||||
|
||||
return@map character
|
||||
}.joinToString("")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.supabase.postgrest.http
|
||||
|
||||
import org.apache.hc.core5.http.Method
|
||||
import java.net.URI
|
||||
|
||||
/**
|
||||
* Interface used by the PostgrestClient, allows replacing the default HTTP client.
|
||||
*
|
||||
* Overwrite it to replace the default Apache HTTP Client implementation.
|
||||
*/
|
||||
interface PostgrestHttpClient {
|
||||
|
||||
fun execute(
|
||||
url: URI,
|
||||
method: Method,
|
||||
headers: Map<String, String> = emptyMap(),
|
||||
body: Any? = null,
|
||||
schema: String? = null,
|
||||
): HttpResponse
|
||||
}
|
||||
|
||||
data class HttpResponse(
|
||||
val status: Int,
|
||||
val body: String?
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
package io.supabase.postgrest.http
|
||||
|
||||
import io.supabase.postgrest.json.PostgrestJsonConverter
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse
|
||||
import org.apache.hc.core5.http.HttpStatus
|
||||
import org.apache.hc.core5.http.Method
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity
|
||||
import java.net.URI
|
||||
|
||||
/**
|
||||
* Default implementation of the [PostgrestHttpClient] used by the PostgrestDefaultClient.
|
||||
*
|
||||
* Uses closable apache HTTP-Client 5.x.
|
||||
*/
|
||||
class PostgrestHttpClientApache(
|
||||
private val httpClient: CloseableHttpClient,
|
||||
private val postgrestJsonConverter: PostgrestJsonConverter
|
||||
) : PostgrestHttpClient {
|
||||
|
||||
override fun execute(url: URI, method: Method, headers: Map<String, String>, body: Any?, schema: String?): HttpResponse {
|
||||
return httpClient.use { httpClient ->
|
||||
val httpRequest = HttpUriRequestBase(method.name, url)
|
||||
body?.apply {
|
||||
val dataAsString = postgrestJsonConverter.serialize(body)
|
||||
httpRequest.entity = StringEntity(dataAsString)
|
||||
}
|
||||
headers.forEach { (name, value) -> httpRequest.addHeader(name, value) }
|
||||
|
||||
return@use httpClient.execute(httpRequest, responseHandler())
|
||||
}
|
||||
}
|
||||
|
||||
private fun responseHandler(): HttpClientResponseHandler<HttpResponse> {
|
||||
return HttpClientResponseHandler<HttpResponse> { response ->
|
||||
throwIfError(response)
|
||||
|
||||
val body = response.entity?.let { EntityUtils.toString(it) }
|
||||
|
||||
return@HttpClientResponseHandler HttpResponse(
|
||||
status = response.code,
|
||||
body = body
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun throwIfError(response: ClassicHttpResponse) {
|
||||
val status = response.code
|
||||
val statusSuccessful = status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION
|
||||
|
||||
if (!statusSuccessful) {
|
||||
val entityAsString = response.entity?.let { EntityUtils.toString(it) }
|
||||
|
||||
throw PostgrestHttpException(status, entityAsString)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package io.supabase.postgrest.http
|
||||
|
||||
/**
|
||||
* Exception is used when a bad status code (> 301) is returned.
|
||||
*
|
||||
* If you implement your custom PostgrestHttpClient, you need to handle exceptions on your own.
|
||||
*
|
||||
* @property[status] HTTP status code
|
||||
* @property[httpBody] Response body as [String] if available
|
||||
*/
|
||||
class PostgrestHttpException(val status: Int, val httpBody: String?) : RuntimeException("Unexpected response status: $status")
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.supabase.postgrest.json
|
||||
|
||||
/**
|
||||
* Interface used by the PostgrestClient, allows replacing the default JSON converter.
|
||||
*
|
||||
* Overwrite it to replace the default Jackson FasterXML implementation.
|
||||
*/
|
||||
interface PostgrestJsonConverter {
|
||||
|
||||
/**
|
||||
* Serializes [data] as JSON string.
|
||||
*
|
||||
* @param[data] the data to serialize
|
||||
*
|
||||
* @return JSON string
|
||||
*/
|
||||
fun serialize(data: Any): String
|
||||
|
||||
/**
|
||||
* Deserializes a JSON [text] to the corresponding [responseType].
|
||||
*
|
||||
* @param[text] The JSON text to convert
|
||||
* @param[responseType] The response type as Java class
|
||||
*/
|
||||
fun <T : Any> deserialize(text: String, responseType: Class<T>): T
|
||||
}
|
||||
|
||||
inline fun <reified T : Any> PostgrestJsonConverter.deserialize(content: String): T = deserialize(content, T::class.java)
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.supabase.postgrest.json
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
|
||||
import com.fasterxml.jackson.module.kotlin.KotlinModule
|
||||
|
||||
/**
|
||||
* Default implementation of the [PostgrestJsonConverter] used by the PostgrestDefaultClient.
|
||||
*
|
||||
* Uses Jackson FasterXML for JSON (de)-serialization.
|
||||
*/
|
||||
class PostgrestJsonConverterJackson : PostgrestJsonConverter {
|
||||
|
||||
private val objectMapper = ObjectMapper()
|
||||
.registerModule(KotlinModule())
|
||||
.registerModule(JavaTimeModule())
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
|
||||
override fun serialize(data: Any): String {
|
||||
return objectMapper.writeValueAsString(data)
|
||||
}
|
||||
|
||||
override fun <T : Any> deserialize(text: String, responseType: Class<T>): T {
|
||||
return objectMapper.readValue(text, responseType)
|
||||
}
|
||||
}
|
||||
|
||||
24
src/test/kotlin/io/supabase/postgrest/PostgresClientTest.kt
Normal file
24
src/test/kotlin/io/supabase/postgrest/PostgresClientTest.kt
Normal file
@@ -0,0 +1,24 @@
|
||||
package io.supabase.postgrest
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.net.URI
|
||||
|
||||
class PostgresClientTest {
|
||||
|
||||
@Test
|
||||
fun foo() {
|
||||
val client = PostgrestDefaultClient(
|
||||
uri = URI("https://eyimuvrqyphojiqwapfv.supabase.co/rest/v1"),
|
||||
defaultHeaders = mapOf("apiKey" to "xyz")
|
||||
)
|
||||
|
||||
val a = client.from<Foo>("foo")
|
||||
.select()
|
||||
.execute()
|
||||
}
|
||||
}
|
||||
|
||||
data class Foo(
|
||||
val id: Long,
|
||||
val text: String
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
package io.supabase.postgrest.json
|
||||
|
||||
import assertk.assertThat
|
||||
import assertk.assertions.isEqualTo
|
||||
import org.junit.jupiter.api.TestInstance
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.MethodSource
|
||||
import java.util.stream.Stream
|
||||
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class PostgrestJsonConverterJackonTest {
|
||||
|
||||
private val converter = PostgrestJsonConverterJackson()
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("serializeData")
|
||||
fun `should serialize and deserialize`(data: Any) {
|
||||
val serialized = converter.serialize(data)
|
||||
|
||||
val deserialized = converter.deserialize(serialized, data.javaClass)
|
||||
|
||||
assertThat(deserialized).isEqualTo(data)
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
private fun serializeData(): Stream<Any> {
|
||||
return Stream.of(
|
||||
"5",
|
||||
mapOf("foo" to "bar", "number" to 5),
|
||||
ConverterTestDto("bar", 5)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
data class ConverterTestDto(
|
||||
val prop: String,
|
||||
val otherProp: Int
|
||||
)
|
||||
Reference in New Issue
Block a user