Skip to content

Commit

Permalink
feat(sdk): change ex.table.get() method and create ex.table.tryGet() …
Browse files Browse the repository at this point in the history
…method (#4108)

fixes #3879

- Change `ex.table.get()` method to throw an error instead of returning `{}` if no row with given key exists.
- Create `ex.table.tryGet()` method to return undefined when no row with the given key exists.

## Checklist

- [x] Title matches [Winglang's style guide](https://www.winglang.io/contributing/start-here/pull_requests#how-are-pull-request-titles-formatted)
- [x] Description explains motivation and solution
- [x] Tests added (always)
- [x] Docs updated (only required for features)
- [ ] Added `pr/e2e-full` label if this feature requires end-to-end testing

*By submitting this pull request, I confirm that my contribution is made under the terms of the [Wing Cloud Contribution License](https://github.com/winglang/wing/blob/main/CONTRIBUTION_LICENSE.md)*.
  • Loading branch information
wzslr321 authored and eladcon committed Sep 13, 2023
1 parent 7c9b735 commit 6c8cd67
Show file tree
Hide file tree
Showing 4 changed files with 209 additions and 0 deletions.
38 changes: 38 additions & 0 deletions examples/tests/sdk_tests/table/get.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
bring cloud;
bring ex;

let table = new ex.Table(
name: "users",
primaryKey: "name",
columns: { "gender" => ex.ColumnType.STRING }
);


test "get" {
let COLUMN_NAME="gender";
let COLUMN_VALUE="male";
let VALID_KEY = "foo";
let NON_EXISTENT_KEY = "bar";
let ROW_DOES_NOT_EXIST_ERROR = "Row does not exist (key=${NON_EXISTENT_KEY})";

let assertThrows = (expected: str, block: (): void) => {
let var error = false;
try {
block();
} catch actual {
assert(actual == expected);
error = true;
}
assert(error);
};

table.insert(VALID_KEY, Json { gender: COLUMN_VALUE });
assert(table.get(VALID_KEY).get(COLUMN_NAME) == COLUMN_VALUE);
assertThrows(ROW_DOES_NOT_EXIST_ERROR, () => {
table.get(NON_EXISTENT_KEY);
});

let var result: Json = table.tryGet(VALID_KEY);
assert(result.get(COLUMN_NAME) == COLUMN_VALUE);
assert(table.tryGet(NON_EXISTENT_KEY) == nil);
}
6 changes: 6 additions & 0 deletions libs/wingsdk/src/.gen/versions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"registry.terraform.io/hashicorp/random": "3.5.1",
"registry.terraform.io/hashicorp/google": "4.63.1",
"registry.terraform.io/hashicorp/azurerm": "3.54.0",
"registry.terraform.io/hashicorp/aws": "4.65.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# [get.w](../../../../../../examples/tests/sdk_tests/table/get.w) | compile | tf-aws

## inflight.$Closure1-1.js
```js
module.exports = function({ $table }) {
class $Closure1 {
constructor({ }) {
const $obj = (...args) => this.handle(...args);
Object.setPrototypeOf($obj, this);
return $obj;
}
async handle() {
const COLUMN_NAME = "gender";
const COLUMN_VALUE = "male";
const VALID_KEY = "foo";
const NON_EXISTENT_KEY = "bar";
const ROW_DOES_NOT_EXIST_ERROR = String.raw({ raw: ["Row does not exist (key=", ")"] }, NON_EXISTENT_KEY);
const assertThrows = async (expected, block) => {
let error = false;
try {
(await block());
}
catch ($error_actual) {
const actual = $error_actual.message;
{((cond) => {if (!cond) throw new Error("assertion failed: actual == expected")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(actual,expected)))};
error = true;
}
{((cond) => {if (!cond) throw new Error("assertion failed: error")})(error)};
}
;
(await $table.insert(VALID_KEY,({"gender": COLUMN_VALUE})));
{((cond) => {if (!cond) throw new Error("assertion failed: table.get(VALID_KEY).get(COLUMN_NAME) == COLUMN_VALUE")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(((obj, args) => { if (obj[args] === undefined) throw new Error(`Json property "${args}" does not exist`); return obj[args] })((await $table.get(VALID_KEY)), COLUMN_NAME),COLUMN_VALUE)))};
(await assertThrows(ROW_DOES_NOT_EXIST_ERROR,async () => {
(await $table.get(NON_EXISTENT_KEY));
}
));
let result = (await $table.tryGet(VALID_KEY));
{((cond) => {if (!cond) throw new Error("assertion failed: result.get(COLUMN_NAME) == COLUMN_VALUE")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(((obj, args) => { if (obj[args] === undefined) throw new Error(`Json property "${args}" does not exist`); return obj[args] })(result, COLUMN_NAME),COLUMN_VALUE)))};
{((cond) => {if (!cond) throw new Error("assertion failed: table.tryGet(NON_EXISTENT_KEY) == nil")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })((await $table.tryGet(NON_EXISTENT_KEY)),undefined)))};
}
}
return $Closure1;
}

```

## main.tf.json
```json
{
"//": {
"metadata": {
"backend": "local",
"stackName": "root",
"version": "0.17.0"
},
"outputs": {
"root": {
"Default": {
"cloud.TestRunner": {
"TestFunctionArns": "WING_TEST_RUNNER_FUNCTION_ARNS"
}
}
}
}
},
"output": {
"WING_TEST_RUNNER_FUNCTION_ARNS": {
"value": "[]"
}
},
"provider": {
"aws": [
{}
]
},
"resource": {
"aws_dynamodb_table": {
"exTable": {
"//": {
"metadata": {
"path": "root/Default/Default/ex.Table/Default",
"uniqueId": "exTable"
}
},
"attribute": [
{
"name": "name",
"type": "S"
}
],
"billing_mode": "PAY_PER_REQUEST",
"hash_key": "name",
"name": "usersex.Table-c840a49c"
}
}
}
}
```

## preflight.js
```js
const $stdlib = require('@winglang/sdk');
const $plugins = ((s) => !s ? [] : s.split(';'))(process.env.WING_PLUGIN_PATHS);
const $outdir = process.env.WING_SYNTH_DIR ?? ".";
const $wing_is_test = process.env.WING_IS_TEST === "true";
const std = $stdlib.std;
const cloud = $stdlib.cloud;
const ex = $stdlib.ex;
class $Root extends $stdlib.std.Resource {
constructor(scope, id) {
super(scope, id);
class $Closure1 extends $stdlib.std.Resource {
constructor(scope, id, ) {
super(scope, id);
(std.Node.of(this)).hidden = true;
}
static _toInflightType(context) {
return `
require("./inflight.$Closure1-1.js")({
$table: ${context._lift(table)},
})
`;
}
_toInflight() {
return `
(await (async () => {
const $Closure1Client = ${$Closure1._toInflightType(this)};
const client = new $Closure1Client({
});
if (client.$inflight_init) { await client.$inflight_init(); }
return client;
})())
`;
}
_getInflightOps() {
return ["handle", "$inflight_init"];
}
_registerBind(host, ops) {
if (ops.includes("handle")) {
$Closure1._registerBindObject(table, host, ["get", "insert", "tryGet"]);
}
super._registerBind(host, ops);
}
}
const table = this.node.root.newAbstract("@winglang/sdk.ex.Table",this,"ex.Table",{ name: "users", primaryKey: "name", columns: ({"gender": ex.ColumnType.STRING}) });
this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:get",new $Closure1(this,"$Closure1"));
}
}
const $App = $stdlib.core.App.for(process.env.WING_TARGET);
new $App({ outdir: $outdir, name: "get", rootConstruct: $Root, plugins: $plugins, isTestEnvironment: $wing_is_test, entrypointDir: process.env['WING_SOURCE_DIR'], rootId: process.env['WING_ROOT_ID'] }).synth();

```
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# [get.w](../../../../../../examples/tests/sdk_tests/table/get.w) | test | sim

## stdout.log
```log
pass ─ get.wsim » root/env0/test:get
Tests 1 passed (1)
Test Files 1 passed (1)
Duration <DURATION>
```

0 comments on commit 6c8cd67

Please sign in to comment.