├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── package.json ├── resources ├── create-dynamodb.sh ├── drop-dynamodb.sh ├── start-dynamodb.sh └── stop-dynamodb.sh ├── solano.yml ├── spec ├── Adapter.spec.ts ├── Expression.spec.ts ├── Parititon.spec.ts └── mocha.opts ├── src ├── Adapter.ts ├── Cache.ts ├── Expression.ts ├── Partition.ts ├── SchemaPartition.ts ├── helpers.ts └── index.ts ├── tsconfig.json ├── typings.json └── vendors └── aws-dynamodb-truncate ├── LICENSE ├── README.md └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ 3 | *.js 4 | *.js.map 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | *.log 3 | *.tgz 4 | logs/ 5 | src/ 6 | spec/ 7 | resources/ 8 | vendors/ 9 | gulpfile.js 10 | tsconfig.json 11 | tslint.json 12 | typings.json 13 | typings 14 | build/spec 15 | *.yml 16 | *.yaml 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | dist: trusty 3 | node_js: 4 | - '6.11' 5 | - '7.10' 6 | - '8.1' 7 | services: 8 | - docker 9 | addons: 10 | hosts: 11 | - dynamodb-local 12 | apt_packages: 13 | - openjdk-8-jre 14 | - python-pip 15 | branches: 16 | only: 17 | - master 18 | - /^[0-9]+.[0-9]+.[0-9]+(-.*)?$/ 19 | cache: 20 | directories: 21 | - node_modules 22 | - /tmp 23 | - resources 24 | - ~/.aws 25 | 26 | # Test stage 27 | stage: test 28 | before_script: 29 | - sudo pip install --upgrade pip 30 | - sudo pip install awscli 31 | - aws configure set region earth 32 | - echo "[default]" > ~/.aws/credentials 33 | - echo "aws_access_key_id = key" >> ~/.aws/credentials 34 | - echo "aws_secret_access_key = secret" >> ~/.aws/credentials 35 | - npm install 36 | - npm install -g typescript 37 | after_script: 38 | - bash <(curl -s https://codecov.io/bash) 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/benishak/parse-server-dynamodb-adapter.svg?branch=master)](https://travis-ci.org/benishak/parse-server-dynamodb-adapter) [![npm version](https://badge.fury.io/js/parse-server-dynamodb-adapter.svg)](https://badge.fury.io/js/parse-server-dynamodb-adapter) 2 | # AWS DynamoDB Parse Server Adapter 3 | 4 | this is database adapter to add support of AWS DynamoDB to Parse Server 5 | 6 | ## Setup 7 | 8 | Create **one** Table using the AWS Console or the AWS API or the AWS CLI with the following parameters 9 | 10 | - **Primary Key** : `_pk_className` 11 | - **Sort Key** : `_sk_id` 12 | 13 | YOU MUST USE THESE KEYS NAME IN ORDER TO USE THIS ADAPTER! 14 | 15 | ### Example creating the table using the CLI 16 | 17 | ``` 18 | pip install awscli // install awscli using python pip 19 | aws configure set region eu-central-1 // set your aws region 20 | aws configure // set your AWS Access Key ID and Secret 21 | aws dynamodb create-table 22 | --table-name parse-server 23 | --attribute-definitions AttributeName=_pk_className,AttributeType=S AttributeName=_sk_id,AttributeType=S 24 | --key-schema AttributeName=_pk_className,KeyType=HASH AttributeName=_sk_id,KeyType=RANGE 25 | --provisioned-throughput ReadCapacityUnits=500,WriteCapacityUnits=1000 26 | ``` 27 | 28 | Please read more about Read/Write Capacity Units [here](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ProvisionedThroughput.html) 29 | 30 | Make sure you provision enough Capacity Units, it depends on your application, if your application is write intensive provision as twice as the read capacity units for your write capacity 31 | 32 | The Read/Write Capacity Units can be changed anytime, but you cannot change the Primary Key and Sort Key once the table is created! 33 | 34 | ### Create AWS IAM User 35 | Learn [here](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.create-user-policy.html) about how to setup an AWS IAM User and generate aws credentials 36 | 37 | If you are using AWS EC2, I suggest using [AWS IAM Roles](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/authentication-and-access-control.html) and attach it to your EC2 Instance instead of IAM Users for better security 38 | 39 | ## Usage 40 | 41 | ``` 42 | var DynamoDB = require('parse-server-dynamodb-adapter').DynamoDB; 43 | var dynamo = new DynamoDB('parse-server', // your DynamoDB Table 44 | { apiVersion: '2012-08-10', // AWS API Version 45 | region : 'eu-central-1', // your AWS Region where you setup your DynamoDB Table 46 | accessKeyId: 'AK....', // your AWS Access Key ID, ignore if you are using IAM Roles 47 | secretAccessKey: 'secret' // your AWS Secret Access Key, ignore if you are using IAM Roles 48 | } 49 | ); 50 | 51 | var api = new ParseServer({ 52 | databaseAdapter: dynamo.getAdapter(), 53 | appId: 'myAppId', 54 | masterKey: 'myMasterKey' 55 | serverURL: 'http://localhost:1337/parse' 56 | ... 57 | }); 58 | ``` 59 | --- 60 | 61 | ## Limits in AWS DynamoDB 62 | 63 | Just like other databases DynamoDB has also some limits that are documented [here](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html): 64 | But the most important limits that you need to know are 65 | 66 | - Maximum Document/Object/Item Size : 400KB (vs 16MB in MongoDB) 67 | - Maximum number of elements in the `$in` query : 100 (vs as many as you want in MongoDB, as long the whole query document size doesn't exceed 16MB) 68 | - Maximum [Expression](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html) Length : 4 KB 69 | 70 | # Compatibility with Parse Server 71 | 72 | Please remember AWS DynamoDB is mainly a key-value Database, this adapter tried its best to simulate how Parse Server works with other Databases like MongoDB, however these features or functions won't work as you expect 73 | 74 | - **Skip** : You cannot use `skip` on your Parse.Query 75 | - **Sort** : If you use `ascending/descending` on any key other than `objectId` with your Parse.Query, the sort will be applied on the query **results** 76 | - **containedIn** : this cannot support huge array more than `98` elements when using Parse.Query 77 | - **containsAll** : you can use this with bigger array however remember that you may hit the maximum length of Expression, which is limited by 4KB 78 | - **Uniqueness** : This adapter impelements uniqueness on the adapter layer, so uniquness is not 100% guaranteed when inserting data in parallel 79 | - **startsWith/contains** : Works with strings but not with RegEx 80 | - **endsWith** : doesn't work, because DynamoDB doesn't support RegEx 81 | - **read consistency** : DynamoDB has an eventually read consistency by default, but this query for the nature of Parse Server is using **strong read consistency**, this may come with extra AWS charges, read more about this topic [here](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html) 82 | - **Array of Pointers** : you can use pointers but you cannot have an ***array of pointers***! we suggest storing only the `objectId` as string like this `Activity.set("users",[User1.id, User2.id, ... ]")` instead of `Activity.set("users", [User1, User2, ... ])` 83 | 84 | --- 85 | 86 | # Usage without Parse Server 87 | 88 | You can use this adapter as a npm module with any project you have without Parse Server 89 | 90 | ``` 91 | var dynamo = new DynamoDB('my-table', // your DynamoDB Table 92 | { apiVersion: '2012-08-10', // AWS API Version 93 | region : 'eu-central-1', // your AWS Region where you setup your DynamoDB Table 94 | accessKeyId: 'AK....', // your AWS Access Key ID, ignore if you are using IAM Roles 95 | secretAccessKey: 'secret' // your AWS Secret Access Key, ignore if you are using IAM Ro$ 96 | } 97 | ); 98 | 99 | var db = dynamo.getAdapter() 100 | var User = db._adaptiveCollection('User'); 101 | User.insertOne({ _id : "1234", "name" : "benishak" }); 102 | User.find({ _id : "1234" }); 103 | 104 | // or using Partiton instance 105 | var Partition = dynamo.Partition; 106 | var User = new Partition('my-table', 'User', dynamo.adapter.service); 107 | User.insertOne({ _id : "1234", "name" : "benishak" }); 108 | User.find({ _id : "1234" }); 109 | User.deleteOne({ _id : "1234" }); 110 | ``` 111 | 112 | I will create a much easier API in next version of this adapter 113 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "parse-server-dynamodb-adapter", 3 | "version": "1.0.8", 4 | "description": "AWS DynamoDB Adapter for Parse Server", 5 | "main": "build/src/index.js", 6 | "scripts": { 7 | "build": "tsc", 8 | "test": "./resources/start-dynamodb.sh && tsc && mocha build/spec && ./resources/stop-dynamodb.sh" 9 | }, 10 | "keywords": ["parse-server", "Parse.com", "Parse Server", "DynamoDB", "AWS", "AWS DynamoDB", "Database", "Adapter", "API", "SDK"], 11 | "homepage": "https://github.com/benishak/parse-server-dynamodb-adapter", 12 | "author": "Ben Ishak", 13 | "license": "Apache-2.0", 14 | "repository" : { 15 | "type" : "git", 16 | "url" : "https://github.com/benishak/parse-server-dynamodb-adapter.git" 17 | }, 18 | "dependencies": { 19 | "@types/aws-sdk": "^2.7.0", 20 | "@types/node": "^7.0.27", 21 | "aws-sdk": "^2.62.0", 22 | "aws-sdk-mock": "^1.7.0", 23 | "bluebird": "^3.5.0", 24 | "parse": "^1.9.2", 25 | "parse-server": "^2.4.2" 26 | }, 27 | "devDependencies": { 28 | "@types/chai": "^3.5.2", 29 | "@types/mocha": "^2.2.41", 30 | "chai": "^3.5.0", 31 | "eslint": "^4.0.0", 32 | "eslint-plugin-flowtype": "^2.34.0", 33 | "express": "^4.15.3", 34 | "jasmine": "^2.6.0", 35 | "jasmine-spec-reporter": "^4.1.0", 36 | "mocha": "^3.3.0", 37 | "mocha-typescript": "^1.1.2", 38 | "nyc": "^11.0.2", 39 | "randomstring": "^1.1.5", 40 | "source-map-support": "^0.4.15" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /resources/create-dynamodb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | aws dynamodb create-table --table-name parse-server --attribute-definitions AttributeName=_pk_className,AttributeType=S AttributeName=_sk_id,AttributeType=S --key-schema AttributeName=_pk_className,KeyType=HASH AttributeName=_sk_id,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 --endpoint-url http://localhost:8000 > /dev/null && sleep 0.1 3 | -------------------------------------------------------------------------------- /resources/drop-dynamodb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | aws dynamodb delete-table --table-name parse-server --endpoint http://localhost:8000 > /dev/null && sleep 0.05 3 | -------------------------------------------------------------------------------- /resources/start-dynamodb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | wget http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz -O /tmp/dynamodb_local_latest.tar.gz \ 3 | && tar -xzf /tmp/dynamodb_local_latest.tar.gz -C /tmp \ 4 | && rm -rf /tmp/dynamodb_local_latest.tar.gz \ 5 | && (nohup java -Djava.library.path=/tmp/DynamoDBLocal_lib -jar /tmp/DynamoDBLocal.jar -inMemory > /dev/null 2>&1 &) \ 6 | && aws dynamodb create-table --table-name parse-server --attribute-definitions AttributeName=_pk_className,AttributeType=S AttributeName=_sk_id,AttributeType=S --key-schema AttributeName=_pk_className,KeyType=HASH AttributeName=_sk_id,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 --endpoint-url http://localhost:8000 && sleep 1 7 | -------------------------------------------------------------------------------- /resources/stop-dynamodb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | aws dynamodb delete-table --table-name parse-server --endpoint http://localhost:8000 && pkill -f 'java.*DynamoDB' && rm -rf /tmp/DynamoDBLocal* 3 | -------------------------------------------------------------------------------- /solano.yml: -------------------------------------------------------------------------------- 1 | test_pattern: 2 | - spec/*.spec.ts 3 | postgresql: 4 | version: '9.1' 5 | mysql: 6 | version: '5.5' 7 | sqlite: false 8 | phantomjs: 9 | version: '1.8.1' -------------------------------------------------------------------------------- /spec/Adapter.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { suite, context, test, slow, timeout } from 'mocha-typescript'; 3 | import { should, expect, assert } from 'chai'; 4 | import { DynamoDB as DAdapter } from '../src/'; 5 | import { Adapter } from '../src/Adapter'; 6 | import { Partition } from '../src/Partition'; 7 | import { DynamoDB } from 'aws-sdk'; 8 | import { newObjectId } from 'parse-server/lib/cryptoUtils'; 9 | import * as Promise from 'bluebird'; 10 | 11 | const AWS = require('aws-sdk-mock'); 12 | 13 | const database = 'parse'; 14 | const settings = { 15 | region : 'eu-central-1', 16 | accessKeyId: 'key', 17 | secretAccessKey: 'secret' 18 | } 19 | 20 | const DDB = new DAdapter('parse-server', { 21 | endpoint : 'http://localhost:8000', 22 | region : 'earth', 23 | accessKeyId : 'key', 24 | secretAccessKey : 'secret', 25 | apiVersion: '2012-08-10' 26 | }); 27 | 28 | const $ = DDB.getAdapter(); 29 | 30 | @suite class DDBAdapter { 31 | 32 | @test 'DynamoDB Adapter : getAdapter'() { 33 | let dynamo = new DAdapter(database, settings); 34 | let adapter = dynamo.getAdapter(); 35 | expect(adapter instanceof Adapter).to.be.true; 36 | expect(adapter.database).to.be.equal(database); 37 | expect(adapter.settings).to.be.equal(settings); 38 | expect(adapter.service instanceof DynamoDB).to.be.true; 39 | } 40 | 41 | @test 'DynamoDB Adapter : Create adaptive Collection'() { 42 | let dynamo = new DAdapter(database, settings); 43 | let adapter = dynamo.getAdapter(); 44 | let partition = adapter._adaptiveCollection('test'); 45 | expect(partition instanceof Partition).to.be.true; 46 | expect(partition.database).to.be.equal(database); 47 | expect(partition.className).to.be.equal('test'); 48 | } 49 | 50 | @test 'DynamoDB Adapter : Return Schema Collection'() { 51 | let dynamo = new DAdapter(database, settings); 52 | let adapter = dynamo.getAdapter(); 53 | let partition = adapter._schemaCollection(); 54 | expect(partition instanceof Partition).to.be.true; 55 | expect(partition.database).to.be.equal(database); 56 | expect(partition.className).to.be.equal('_SCHEMA'); 57 | } 58 | } 59 | 60 | @suite class DDBSOps { 61 | 62 | before(done) { 63 | $.deleteAllClasses().then(() => { 64 | done(); 65 | }); 66 | } 67 | 68 | @test 'stores objectId in _id'(done) { 69 | $.createObject('Foo', { fields: {} }, { objectId: 'abcde' }) 70 | .then(() => $._rawFind('Foo')) 71 | .then(results => { 72 | expect(results.length).to.be.equal(1); 73 | var obj = results[0]; 74 | expect(obj._id).to.be.equal('abcde'); 75 | expect(obj.objectId).to.be.undefined; 76 | done(); 77 | }); 78 | } 79 | 80 | @test 'stores pointers with a _p_ prefi'(done) { 81 | const obj = { 82 | objectId: 'bar', 83 | aPointer: { 84 | __type: 'Pointer', 85 | className: 'JustThePointer', 86 | objectId: 'qwerty' 87 | } 88 | } 89 | 90 | $.createObject('APointerDarkly', { 91 | fields: { 92 | objectId: { type: 'String' }, 93 | aPointer: { type: 'Pointer', targetClass: 'JustThePointer' }, 94 | } 95 | }, obj) 96 | .then(() => $._rawFind('APointerDarkly')) 97 | .then(results => { 98 | expect(results.length).to.be.equal(1); 99 | const output = results[0]; 100 | expect(typeof output._id).to.be.equal('string'); 101 | expect(typeof output._p_aPointer).to.be.equal('string'); 102 | expect(output._p_aPointer).to.be.equal('JustThePointer$qwerty'); 103 | expect(output.aPointer).to.be.undefined; 104 | done(); 105 | }); 106 | } 107 | 108 | @test 'handles object and subdocument'(done) { 109 | const schema = { objectId: { type : 'String' }, fields : { subdoc: { type: 'Object' } } }; 110 | const objectId = newObjectId(); 111 | const className = 'MyClass'; 112 | 113 | const obj = { 114 | objectId: objectId, 115 | subdoc: {foo: 'bar', wu: 'tan'} 116 | }; 117 | $.createObject(className, schema, obj) 118 | .then(() => $._rawFind(className)) 119 | .then(results => { 120 | expect(results.length).to.be.equal(1); 121 | const mob = results[0]; 122 | expect(typeof mob.subdoc).to.be.equal('object'); 123 | expect(mob.subdoc.foo).to.be.equal('bar'); 124 | expect(mob.subdoc.wu).to.be.equal('tan'); 125 | const obj = { 126 | subdoc : { 127 | foo : 'bar', 128 | wu : 'clan' 129 | } 130 | } 131 | return $.findOneAndUpdate(className, schema, { objectId: objectId }, obj); 132 | }) 133 | .then(() => $._rawFind(className)) 134 | .then(results => { 135 | expect(results.length).to.be.equal(1); 136 | const mob = results[0]; 137 | expect(typeof mob.subdoc).to.be.equal('object'); 138 | expect(mob.subdoc.foo).to.be.equal('bar'); 139 | expect(mob.subdoc.wu).to.be.equal('clan'); 140 | done(); 141 | }) 142 | .catch(error => { 143 | console.log(error); 144 | expect(error).to.be.undefined; 145 | done(); 146 | }) 147 | } 148 | 149 | @test 'handles creating an array, object, date, file'(done) { 150 | const adapter = $; 151 | const objectId = newObjectId(); 152 | const className = 'MyClass'; 153 | 154 | const obj = { 155 | objectId : objectId, 156 | array: [1, 2, 3], 157 | object: {foo: 'bar'}, 158 | date: { 159 | __type: 'Date', 160 | iso: '2016-05-26T20:55:01.154Z', 161 | }, 162 | file: { 163 | __type: 'File', 164 | name: '7aefd44420d719adf65d16d52e688baf_license.txt', 165 | url: 'http://localhost:1337/files/app/7aefd44420d719adf65d16d52e688baf_license.txt' 166 | } 167 | }; 168 | const schema = { 169 | fields: { 170 | array: { type: 'Array' }, 171 | object: { type: 'Object' }, 172 | date: { type: 'Date' }, 173 | file: { type: 'File' } 174 | } 175 | }; 176 | adapter.createObject(className, schema, obj) 177 | .then(() => adapter._rawFind(className, {})) 178 | .then(results => { 179 | expect(results.length).to.be.equal(1); 180 | const mob = results[0]; 181 | expect(mob.array instanceof Array).to.be.equal(true); 182 | expect(typeof mob.object).to.be.equal('object'); 183 | expect(typeof mob.date).to.be.equal('string'); 184 | return adapter.find(className, schema, {}, {}); 185 | }) 186 | .then(results => { 187 | expect(results.length).to.be.equal(1); 188 | const mob = results[0]; 189 | expect(mob.objectId).to.be.equal(objectId); 190 | expect(mob.array instanceof Array).to.be.equal(true); 191 | expect(typeof mob.object).to.be.equal('object'); 192 | expect(mob.date.iso).to.be.equal('2016-05-26T20:55:01.154Z'); 193 | expect(mob.file.__type).to.be.equal('File'); 194 | done(); 195 | }) 196 | .catch(error => { 197 | console.log(error); 198 | expect(error).to.be.undefined; 199 | done(); 200 | }); 201 | } 202 | 203 | @test 'handles updating a single object with array, object, date'(done) { 204 | const adapter = $; 205 | const objectId = newObjectId(); 206 | const className = 'MyClass'; 207 | 208 | const schema = { 209 | fields: { 210 | array: { type: 'Array' }, 211 | object: { type: 'Object' }, 212 | date: { type: 'Date' }, 213 | } 214 | }; 215 | 216 | 217 | adapter.createObject(className, schema, { objectId: objectId }) 218 | .then(() => adapter._rawFind(className)) 219 | .then(results => { 220 | expect(results.length).to.be.equal(1); 221 | const update = { 222 | array: [1, 2, 3], 223 | object: {foo: 'bar'}, 224 | date: { 225 | __type: 'Date', 226 | iso: '2016-05-26T20:55:01.154Z', 227 | }, 228 | }; 229 | const query = { objectId: objectId }; 230 | return adapter.findOneAndUpdate(className, schema, query, update) 231 | }) 232 | .then(results => { 233 | console.log(results); 234 | const mob = results; 235 | expect(mob.array instanceof Array).to.be.equal(true); 236 | expect(typeof mob.object).to.be.equal('object'); 237 | expect(typeof mob.date).to.be.equal('object'); 238 | expect(mob.date.iso).to.be.equal('2016-05-26T20:55:01.154Z'); 239 | return adapter._rawFind(className); 240 | }) 241 | .then(results => { 242 | expect(results.length).to.be.equal(1); 243 | const mob = results[0]; 244 | expect(mob.array instanceof Array).to.be.equal(true); 245 | expect(typeof mob.object).to.be.equal('object'); 246 | expect(typeof mob.date).to.be.equal('string'); 247 | expect(mob.date).to.be.equal('2016-05-26T20:55:01.154Z'); 248 | done(); 249 | }) 250 | .catch(error => { 251 | console.log(error); 252 | expect(error).to.be.undefined; 253 | done(); 254 | }); 255 | } 256 | } -------------------------------------------------------------------------------- /spec/Expression.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { suite, test, slow, timeout } from 'mocha-typescript'; 3 | import { should, expect, assert } from 'chai'; 4 | import { Partition } from '../src/Partition'; 5 | import { Expression as Query } from '../src/Expression'; 6 | 7 | const AWS = require('aws-sdk-mock'); 8 | 9 | const __ops0 = ['$eq', '$gt', '$gte', '$lt', '$lt', '$lte']; 10 | const __ops1 = ['$eq', '$ne', '$gt', '$gte', '$lt', '$lt', '$lte']; 11 | const __ops2 = ['$exists']; 12 | 13 | @suite class DDBExpression { 14 | 15 | @test 'can generate simple expression from key : foo'() { 16 | let exp = new Query(); 17 | let text = exp.createExpression('foo', 'bar', '='); 18 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 19 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':foo_0'); 20 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 21 | expect(exp.ExpressionAttributeValues[':foo_0']).to.be.equal('bar'); 22 | expect(text).to.be.equal('#foo = :foo_0'); 23 | } 24 | 25 | @test 'can generate expression from nested key : foo.bar'() { 26 | let exp = new Query(); 27 | let text = exp.createExpression('foo.bar', 'foobar', '='); 28 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 29 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#bar'); 30 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':bar_0'); 31 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 32 | expect(exp.ExpressionAttributeNames['#bar']).to.be.equal('bar'); 33 | expect(exp.ExpressionAttributeValues[':bar_0']).to.be.equal('foobar'); 34 | expect(text).to.be.equal('#foo.#bar = :bar_0'); 35 | } 36 | 37 | @test 'can generate expression from nested key : foo.bar.foobar'() { 38 | let exp = new Query(); 39 | let text = exp.createExpression('foo.bar.foobar', 'foobar', '='); 40 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 41 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#bar'); 42 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':foobar_0'); 43 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 44 | expect(exp.ExpressionAttributeNames['#bar']).to.be.equal('bar'); 45 | expect(exp.ExpressionAttributeValues[':foobar_0']).to.be.equal('foobar'); 46 | expect(text).to.be.equal('#foo.#bar.#foobar = :foobar_0'); 47 | } 48 | 49 | @test 'can generate expression from list element : foo[0]'() { 50 | let exp = new Query(); 51 | let text = exp.createExpression('foo[0]', 'bar', '='); 52 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 53 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':foo_0'); 54 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 55 | expect(exp.ExpressionAttributeValues[':foo_0']).to.be.equal('bar'); 56 | expect(text).to.be.equal('#foo[0] = :foo_0'); 57 | } 58 | 59 | @test 'can generate expression from list element : foo[0][1]'() { 60 | let exp = new Query(); 61 | let text = exp.createExpression('foo[0][1]', 'bar', '='); 62 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 63 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':foo_0'); 64 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 65 | expect(exp.ExpressionAttributeValues[':foo_0']).to.be.equal('bar'); 66 | expect(text).to.be.equal('#foo[0][1] = :foo_0'); 67 | } 68 | 69 | @test 'can generate expression of nested list element : foo.bar[0]'() { 70 | let exp = new Query(); 71 | let text = exp.createExpression('foo.bar[0]', 'foobar', '='); 72 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 73 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#bar'); 74 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':bar_0'); 75 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 76 | expect(exp.ExpressionAttributeNames['#bar']).to.be.equal('bar'); 77 | expect(exp.ExpressionAttributeValues[':bar_0']).to.be.equal('foobar'); 78 | expect(text).to.be.equal('#foo.#bar[0] = :bar_0'); 79 | } 80 | 81 | @test 'can generate expression of nested list elements : foo[0].bar[0]'() { 82 | let exp = new Query(); 83 | let text = exp.createExpression('foo[0].bar[0]', 'foobar', '='); 84 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 85 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#bar'); 86 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':bar_0'); 87 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('foo'); 88 | expect(exp.ExpressionAttributeNames['#bar']).to.be.equal('bar'); 89 | expect(exp.ExpressionAttributeValues[':bar_0']).to.be.equal('foobar'); 90 | expect(text).to.be.equal('#foo[0].#bar[0] = :bar_0'); 91 | } 92 | 93 | @test 'can generate expression of mixed nested list elements : foo[0][1].bar[0].foobar[2]'() { 94 | let exp = new Query(); 95 | let text = exp.createExpression('_foo[0][1].__bar[0].foobar[2]', '123', '='); 96 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#foo'); 97 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#bar'); 98 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':foobar_0'); 99 | expect(exp.ExpressionAttributeNames['#foo']).to.be.equal('_foo'); 100 | expect(exp.ExpressionAttributeNames['#bar']).to.be.equal('__bar'); 101 | expect(exp.ExpressionAttributeValues[':foobar_0']).to.be.equal('123'); 102 | expect(text).to.be.equal('#foo[0][1].#bar[0].#foobar[2] = :foobar_0'); 103 | } 104 | 105 | @test 'DynamoDB FilterExpression : should generate simple query with single key'() { 106 | let exp = new Query(); 107 | exp.build({ 108 | "string" : "abc" 109 | }); 110 | 111 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(1); 112 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(1); 113 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#string'); 114 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':string_0'); 115 | expect(exp.ExpressionAttributeNames['#string']).to.be.equal('string'); 116 | expect(exp.ExpressionAttributeValues[':string_0']).to.be.equal('abc'); 117 | expect(exp.Expression).to.be.equal('#string = :string_0'); 118 | } 119 | 120 | @test 'DynamoDB FilterExpression : should generate single query with single key'() { 121 | __ops1.forEach( 122 | op => { 123 | let exp = new Query(); 124 | exp.build({ 125 | field : { 126 | [op] : 1 127 | } 128 | }); 129 | 130 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(1); 131 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(1); 132 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#field'); 133 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':field_0'); 134 | expect(exp.ExpressionAttributeNames['#field']).to.be.equal('field'); 135 | expect(exp.ExpressionAttributeValues[':field_0']).to.be.equal(1); 136 | expect(exp.Expression).to.be.equal( 137 | '#field [op] :field_0'.replace('[op]', exp.comperators[op]) 138 | ) 139 | } 140 | ) 141 | } 142 | 143 | @test 'DynamoDB FilterExpression : should generate range query of signle key'() { 144 | let exp = new Query(); 145 | exp.build({ 146 | balance : { 147 | $gt : 1000, 148 | $lt : 2000 149 | } 150 | }); 151 | 152 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(1); 153 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(2); 154 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#balance'); 155 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':balance_0'); 156 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':balance_1'); 157 | expect(exp.ExpressionAttributeNames['#balance']).to.be.equal('balance'); 158 | expect(exp.ExpressionAttributeValues[':balance_0']).to.be.equal(1000); 159 | expect(exp.ExpressionAttributeValues[':balance_1']).to.be.equal(2000); 160 | expect((exp.Expression.match(/AND/g) || []).length).to.be.equal(1); 161 | expect(exp.Expression).to.be.equal( 162 | '#balance > :balance_0 AND #balance < :balance_1' 163 | ); 164 | } 165 | 166 | @test 'DynamoDB FilterExpression : should generate range query of signle key with $and'() { 167 | let exp = new Query(); 168 | exp.build({ $and : [ 169 | { balance : { $gt : 1000 } }, 170 | { balance : { $lt : 2000 } } 171 | ]}); 172 | 173 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(1); 174 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(2); 175 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#balance'); 176 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':balance_0'); 177 | expect(exp.ExpressionAttributeValues).to.haveOwnProperty(':balance_1'); 178 | expect(exp.ExpressionAttributeNames['#balance']).to.be.equal('balance'); 179 | expect(exp.ExpressionAttributeValues[':balance_0']).to.be.equal(1000); 180 | expect(exp.ExpressionAttributeValues[':balance_1']).to.be.equal(2000); 181 | expect((exp.Expression.match(/AND/g) || []).length).to.be.equal(1); 182 | expect(exp.Expression).to.be.equal( 183 | '#balance > :balance_0 AND #balance < :balance_1' 184 | ); 185 | } 186 | 187 | @test 'DynamoDB FilterExpression : should generate nested $or query of $ands'() { 188 | let exp = new Query(); 189 | exp.build({ $and : [ 190 | { 191 | $or : [ 192 | { balance : { $gt : 1000 } }, 193 | { balance : { $lt : 2000 } } 194 | ] 195 | }, 196 | { 197 | $or : [ 198 | { quantity : { $ne : 0 } }, 199 | { quantity : { $ne : 5000 } } 200 | ] 201 | } 202 | ]}); 203 | 204 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(2); 205 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(4); 206 | expect(exp.Expression).to.be.equal( 207 | '( #balance > :balance_0 OR #balance < :balance_1 ) AND ( #quantity <> :quantity_0 OR #quantity <> :quantity_1 )' 208 | ); 209 | } 210 | 211 | @test 'DynamoDB FilterExpression : should generate $and query with multiple keys'() { 212 | let exp = new Query(); 213 | exp.build({ $and : [ 214 | { balance : { $gt : 1000 } }, 215 | { balance : { $lt : 2000 } }, 216 | { quantity : { $eq : 5 } }, 217 | { product : 'book' } 218 | ]}); 219 | 220 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(3); 221 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(4); 222 | expect((exp.Expression.match(/AND/g) || []).length).to.be.equal(3); 223 | expect(exp.Expression).to.be.equal( 224 | '#balance > :balance_0 AND #balance < :balance_1 AND #quantity = :quantity_0 AND #product = :product_0' 225 | ); 226 | } 227 | 228 | @test 'DynamoDB FilterExpression : should generate simple query with multiple keys without operator'() { 229 | let exp = new Query(); 230 | exp.build({ 231 | "string" : "string", 232 | "number" : 1, 233 | "date" : new Date().toISOString(), 234 | "double" : 1.5, 235 | "array" : [ 1, 2 ,3 ], 236 | "object" : { 237 | key1 : 'value1', 238 | key2 : 'value2' 239 | } 240 | }); 241 | 242 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(6); 243 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(6); 244 | expect(Object.keys(exp.ExpressionAttributeNames).sort().join()).to.be.equal( 245 | ['#string','#number','#object','#array','#double','#date'].sort().join() 246 | ) 247 | expect(Object.keys(exp.ExpressionAttributeValues).sort().join()).to.be.equal( 248 | [':string_0',':number_0',':object_0',':array_0',':double_0',':date_0'].sort().join() 249 | ) 250 | expect((exp.Expression.match(/AND/g) || []).length).to.be.equal(5); 251 | expect(exp.Expression).to.be.equal( 252 | '#string [op] :string_0 AND #number [op] :number_0 AND #date [op] :date_0 AND #double [op] :double_0 AND #array = :array_0 AND #object = :object_0'.replace(/\[op\]/g, '=') 253 | ) 254 | } 255 | 256 | @test 'DynamoDB FilterExpression : should generate simple query with multiple keys'() { 257 | __ops1.forEach( 258 | op => { 259 | let exp = new Query(); 260 | exp.build({ 261 | "string" : { 262 | [op] : "string" 263 | }, 264 | "number" : { 265 | [op] : 1 266 | }, 267 | "date" : { 268 | [op] : (new Date()).toISOString() 269 | }, 270 | "double" : { 271 | [op] : 1.5 272 | }, 273 | "array" : { 274 | '$eq' : [1,2,3] 275 | }, 276 | "object" : { 277 | '$eq' : { 278 | key1 : 'value2', 279 | key2 : 'value2' 280 | } 281 | } 282 | }); 283 | 284 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(6); 285 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(6); 286 | expect(Object.keys(exp.ExpressionAttributeNames).sort().join()).to.be.equal( 287 | ['#string','#number','#object','#array','#double','#date'].sort().join() 288 | ) 289 | expect(Object.keys(exp.ExpressionAttributeValues).sort().join()).to.be.equal( 290 | [':string_0',':number_0',':object_0',':array_0',':double_0',':date_0'].sort().join() 291 | ) 292 | expect((exp.Expression.match(/AND/g) || []).length).to.be.equal(5); 293 | expect(exp.Expression).to.be.equal( 294 | '#string [op] :string_0 AND #number [op] :number_0 AND #date [op] :date_0 AND #double [op] :double_0 AND #array = :array_0 AND #object = :object_0'.replace(/\[op\]/g, exp.comperators[op]) 295 | ) 296 | } 297 | ) 298 | } 299 | 300 | @test 'DynamoDB FilterExpression : should generate $or query of signle key'() { 301 | let exp = new Query(); 302 | exp.build({ $or : [ 303 | { balance : { $gt : 1000, $ne : 5000 } }, 304 | { balance : { $lt : 2000, $ne : 0 } }, 305 | ]}); 306 | 307 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.be.equal(1); 308 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.be.equal(4); 309 | expect(exp.ExpressionAttributeNames).to.haveOwnProperty('#balance'); 310 | expect(exp.ExpressionAttributeNames['#balance']).to.be.equal('balance'); 311 | expect(exp.ExpressionAttributeValues[':balance_0']).to.be.equal(1000); 312 | expect(exp.ExpressionAttributeValues[':balance_1']).to.be.equal(5000); 313 | expect(exp.ExpressionAttributeValues[':balance_2']).to.be.equal(2000); 314 | expect(exp.ExpressionAttributeValues[':balance_3']).to.be.equal(0); 315 | expect(exp.Expression).to.be.equal( 316 | '( #balance > :balance_0 AND #balance <> :balance_1 ) OR ( #balance < :balance_2 AND #balance <> :balance_3 )' 317 | ); 318 | } 319 | 320 | @test 'DynamoDB FilterExpression : should generate nested complex $or query of $ands'() { 321 | let exp = new Query(); 322 | exp.build({ $or : [ 323 | { 324 | $and : [ 325 | { balance : { $gt : 1000 } }, 326 | { balance : { $lt : 2000 } } 327 | ] 328 | }, 329 | { 330 | $and : [ 331 | { quantity : { $ne : 0 } }, 332 | { quantity : { $ne : 5000 } }, 333 | { product : { $in : ['book', 'CD'] } }, 334 | { stat : { $nin : ['old', 'used'] } }, 335 | { author : { $not : { $ne : 'abc' } } }, 336 | { $or : [ 337 | { stars : 5 }, 338 | { stars : { $exists : 0 } } 339 | ]} 340 | ] 341 | } 342 | ]}); 343 | 344 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.equal(6); 345 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.equal(10); 346 | expect(exp.Expression).to.equal( 347 | '#balance > :balance_0 AND #balance < :balance_1 OR #quantity <> :quantity_0 AND #quantity <> :quantity_1 AND #product IN (:product_0_0,:product_0_1) AND NOT ( #stat IN (:stat_0_0,:stat_0_1) ) AND #author = :author_0 AND ( #stars = :stars_0 OR attribute_not_exists(#stars) )' 348 | ); 349 | } 350 | 351 | @test 'DynamoDB FilterExpression : $and query with empty subquery'() { 352 | let exp = new Query(); 353 | exp.build({ '$and': [ {}, { _p_user: '_User$vtp2pCZmv2' } ], 354 | _rperm: { '$in': [ null, '*', 'vtp2pCZmv2' ] } }); 355 | 356 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.equal(2); 357 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.equal(4); 358 | expect(exp.ExpressionAttributeValues[':null']).to.equal(null); 359 | expect(exp.Expression).to.equal( 360 | '#p_user = :p_user_0 AND ( contains(#rperm,:rperm_0_0) OR contains(#rperm,:rperm_0_1) OR attribute_not_exists(#rperm) OR #rperm = :null )' 361 | ); 362 | } 363 | 364 | @test 'DynamoDB FilterExpression : applying more than one query on same key 1'() { 365 | let exp = new Query(); 366 | exp.build({ _id: { '$eq': 'unWCHGvGFE', '$nin': [ '8q4qVagG1h', 'unWCHGvGFE' ] }, 367 | _rperm: { '$in': [ null, '*', '3sRA9jCEGC' ] } }); 368 | 369 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.equal(2); 370 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.equal(6); 371 | expect(exp.ExpressionAttributeValues[':null']).to.equal(null); 372 | expect(exp.Expression).to.equal( 373 | '#id = :id_0 AND NOT ( #id IN (:id_1_0,:id_1_1) ) AND ( contains(#rperm,:rperm_0_0) OR contains(#rperm,:rperm_0_1) OR attribute_not_exists(#rperm) OR #rperm = :null )' 374 | ); 375 | } 376 | 377 | @test 'DynamoDB FilterExpression : applying more than one query on same key 2'() { 378 | let exp = new Query(); 379 | exp.build({ _id: 380 | { '$in': 381 | [ 'G0kOG5lMpz', 382 | 'eLrvwTQ25l', 383 | 'NDteakhAun', 384 | 'NDteakhAun', 385 | 'eLrvwTQ25l' ], 386 | '$nin': [ 'NDteakhAun', 'eLrvwTQ25l' ] 387 | } 388 | }); 389 | 390 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.equal(1); 391 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.equal(7); 392 | expect(exp.Expression).to.equal( 393 | '#id IN (:id_0_0,:id_0_1,:id_0_2,:id_0_3,:id_0_4) AND NOT ( #id IN (:id_5_0,:id_5_1) )' 394 | ); 395 | } 396 | 397 | @test 'DynamoDB FilterExpression : can do $all containsAll'() { 398 | let exp = new Query(); 399 | exp.build({ numbers: { '$all': [ 1, 2, 3 ] } }); 400 | 401 | expect(Object.keys(exp.ExpressionAttributeNames).length).to.equal(1); 402 | expect(Object.keys(exp.ExpressionAttributeValues).length).to.equal(3); 403 | expect(exp.Expression).to.equal( 404 | '( contains(#numbers,:numbers_0_0) AND contains(#numbers,:numbers_0_1) AND contains(#numbers,:numbers_0_2) )' 405 | ); 406 | } 407 | 408 | @test 'DynamoDB UpdateExpression : set one attribute'() { 409 | let params = {}; 410 | let exp = Query.getUpdateExpression({ 411 | foo : 'bar' 412 | }, params); 413 | let vl = Object.keys(params['ExpressionAttributeValues'])[0]; 414 | 415 | expect(exp).to.be.equal('SET #foo = ' + vl); 416 | 417 | params = {}; 418 | exp = Query.getUpdateExpression({ 419 | $set : { 420 | foo : 'bar' 421 | } 422 | }, params) 423 | vl = Object.keys(params['ExpressionAttributeValues'])[0]; 424 | 425 | expect(exp).to.be.equal('SET #foo = ' + vl); 426 | } 427 | 428 | @test 'DynamoDB UpdateExpression : inc one attribute'() { 429 | let params = {}; 430 | let exp = Query.getUpdateExpression({ 431 | $inc : { 432 | foo : 1 433 | } 434 | }, params); 435 | let vl = Object.keys(params['ExpressionAttributeValues'])[0]; 436 | 437 | expect(exp).to.be.equal('SET #foo = if_not_exists(#foo,:__zero__) + :foo_0'); 438 | } 439 | 440 | @test 'DynamoDB UpdateExpression : can handle $nin with other attributes'() { 441 | let params = {}; 442 | let exp = new Query(); 443 | exp = exp.build({ 444 | objectId: { 445 | '$nin': [ '2ohGZeLub2', 'RGtEPnwICo' ], 446 | '$in': [ 'RGtEPnwICo', '2ohGZeLub2', 'r3YPI7akbe', 'RGtEPnwICo', '2ohGZeLub2' ] 447 | }, 448 | _rperm: { '$in': [ null, '*', 'XJbcIDTTON' ] } 449 | }); 450 | 451 | expect(exp.Expression).to.be.equal( 452 | 'NOT ( #objectid IN (:objectid_0_0,:objectid_0_1) ) AND #objectid IN (:objectid_2_0,:objectid_2_1,:objectid_2_2,:objectid_2_3,:objectid_2_4) AND ( contains(#rperm,:rperm_0_0) OR contains(#rperm,:rperm_0_1) OR attribute_not_exists(#rperm) OR #rperm = :null )' 453 | ); 454 | } 455 | 456 | @test 'DynamoDB UpdateExpression : can handle $nin with other attributes combined with $not'() { 457 | let params = {}; 458 | let exp = new Query(); 459 | exp = exp.build({ 460 | objectId: { 461 | '$not' : { '$nin': [ '2ohGZeLub2', 'RGtEPnwICo' ] }, 462 | '$in': [ 'RGtEPnwICo', '2ohGZeLub2', 'r3YPI7akbe', 'RGtEPnwICo', '2ohGZeLub2' ] 463 | }, 464 | _rperm: { '$in': [ null, '*', 'XJbcIDTTON' ] } 465 | }); 466 | 467 | expect(exp.Expression).to.be.equal( 468 | '#objectid IN (:objectid_0_0,:objectid_0_1) AND #objectid IN (:objectid_2_0,:objectid_2_1,:objectid_2_2,:objectid_2_3,:objectid_2_4) AND ( contains(#rperm,:rperm_0_0) OR contains(#rperm,:rperm_0_1) OR attribute_not_exists(#rperm) OR #rperm = :null )' 469 | ); 470 | } 471 | 472 | @test 'DynamoDB UpdateExpression : $or/and with one query'() { 473 | let params = {}; 474 | let exp = new Query(); 475 | exp = exp.build({ 476 | $or : [ { _id : 10 } ] 477 | }); 478 | 479 | expect(exp.Expression).to.be.equal( 480 | '#id = :id_0' 481 | ); 482 | 483 | exp = exp.build({ 484 | $and : [ { _id : 10 } ] 485 | }); 486 | 487 | expect(exp.Expression).to.be.equal( 488 | '#id = :id_0' 489 | ); 490 | } 491 | 492 | @test 'DynamoDB UpdateExpression : empty $or/$and'() { 493 | let params = {}; 494 | let exp = new Query(); 495 | exp = exp.build({ 496 | $or : [] 497 | }); 498 | 499 | expect(exp.Expression).to.be.equal( 500 | '[first]' 501 | ); 502 | 503 | exp = exp.build({ 504 | $and : [] 505 | }); 506 | 507 | expect(exp.Expression).to.be.equal( 508 | '[first]' 509 | ); 510 | 511 | exp = exp.build({ 512 | $and : [ 513 | { 514 | $or : [] 515 | } 516 | ] 517 | }); 518 | 519 | expect(exp.Expression).to.be.equal( 520 | '[first]' 521 | ); 522 | 523 | exp = exp.build({ 524 | $or : [ 525 | { 526 | $and : [] 527 | } 528 | ] 529 | }); 530 | 531 | expect(exp.Expression).to.be.equal( 532 | '[first]' 533 | ); 534 | } 535 | 536 | } -------------------------------------------------------------------------------- /spec/Parititon.spec.ts: -------------------------------------------------------------------------------- 1 | // based on /parse-server/blob/master/spec/Mongo*.spec.js 2 | /// 3 | import { suite, test, slow, timeout } from 'mocha-typescript'; 4 | import { should, expect, assert } from 'chai'; 5 | import { DynamoDB as DAdapter } from '../src/'; 6 | import { Partition } from '../src/Partition'; 7 | import { SchemaPartition as Schema, mongoSchemaToParseSchema } from '../src/SchemaPartition'; 8 | import { Adapter } from '../src/Adapter'; 9 | 10 | const DDB = new DAdapter('parse-server', { 11 | endpoint : 'http://localhost:8000', 12 | region : 'earth', 13 | accessKeyId : 'key', 14 | secretAccessKey : 'secret' 15 | }); 16 | 17 | const $ = DDB.getAdapter(); 18 | 19 | @suite class DDBSchemaParititon { 20 | 21 | } -------------------------------------------------------------------------------- /spec/mocha.opts: -------------------------------------------------------------------------------- 1 | --ui mocha-typescript 2 | --require source-map-support/register 3 | *.ts -------------------------------------------------------------------------------- /src/Adapter.ts: -------------------------------------------------------------------------------- 1 | import { DynamoDB } from 'aws-sdk'; 2 | import * as Promise from 'bluebird'; 3 | import * as Transform from 'parse-server/lib/Adapters/Storage/Mongo/MongoTransform'; 4 | import { Partition } from './Partition'; 5 | import { _Cache as Cache } from './Cache'; 6 | import { SchemaPartition, mongoSchemaToParseSchema, parseFieldTypeToMongoFieldType } from './SchemaPartition'; 7 | import { Parse } from 'parse/node'; 8 | import { _ } from 'lodash'; 9 | import { newObjectId } from 'parse-server/lib/cryptoUtils'; 10 | 11 | type Options = { 12 | skip? : Object, // not supported 13 | limit? : number, 14 | sort? : Object, // only supported on partition/sort key 15 | keys? : Object 16 | count?: boolean 17 | } 18 | 19 | const schemaPartition = '_SCHEMA'; 20 | 21 | // not used at the moment but can be helpful in the future! 22 | const DynamoType = type => { 23 | switch (type.type) { 24 | case 'String': return 'S'; // string 25 | case 'Date': return 'S'; // string 26 | case 'Object': return 'M'; // object 27 | case 'File': return 'M'; // object 28 | case 'Boolean': return 'BOOL'; // boolean 29 | case 'Pointer': return 'S'; // string 30 | case 'Relation' : return 'M'; // string 31 | case 'Number': return 'N'; // number 32 | case 'GeoPoint': return 'M'; // object 33 | case 'Array': 34 | if (type.contents && type.contents.type === 'String') { 35 | return 'SS'; // string[] 36 | } else if (type.contents && type.contents.type === 'Number') { 37 | return 'NS'; // number[] 38 | } else { 39 | return 'L'; // array 40 | } 41 | default: throw `no type for ${JSON.stringify(type)} yet`; 42 | } 43 | }; 44 | 45 | Transform.convertParseSchemaToMongoSchema = ({...schema}) => { 46 | delete schema.fields._rperm; 47 | delete schema.fields._wperm; 48 | 49 | if (schema.className === '_User') { 50 | delete schema.fields._hashed_password; 51 | } 52 | 53 | return schema; 54 | } 55 | 56 | Transform.mongoSchemaFromFieldsAndClassNameAndCLP = (fields, className, classLevelPermissions) => { 57 | const mongoObject = { 58 | _id: className, 59 | objectId: 'string', 60 | updatedAt: 'string', 61 | createdAt: 'string' 62 | }; 63 | 64 | for (const fieldName in fields) { 65 | mongoObject[fieldName] = parseFieldTypeToMongoFieldType(fields[fieldName]); 66 | } 67 | 68 | if (typeof classLevelPermissions !== 'undefined') { 69 | mongoObject['_metadata'] = mongoObject['_metadata'] || {}; 70 | if (!classLevelPermissions) { 71 | delete mongoObject['_metadata'].class_permissions; 72 | } else { 73 | mongoObject['_metadata'].class_permissions = classLevelPermissions; 74 | } 75 | } 76 | 77 | return mongoObject; 78 | } 79 | 80 | Transform.transformToParseObject = (className, mongoObject, schema) => { 81 | const object = Transform.mongoObjectToParseObject(className, mongoObject, schema); 82 | if (object instanceof Object) { 83 | Object.keys(schema.fields|| {}).forEach(k => { 84 | if ((schema.fields[k].type || '').toLowerCase() == 'date' && typeof object[k] == 'string' && ['createdAt', 'updatedAt'].indexOf(k) == -1) { 85 | object[k] = Parse._encode(new Date(object[k])); 86 | } 87 | }); 88 | 89 | if (className == '_User') { 90 | if (object['_password_changed_at']) { 91 | object['_password_changed_at'] = Parse._encode(new Date(object['_password_changed_at'])); 92 | } 93 | 94 | if (object['_email_verify_token_expires_at']) { 95 | object['_email_verify_token_expires_at'] = Parse._encode(new Date(object['_email_verify_token_expires_at'])); 96 | } 97 | } 98 | } 99 | 100 | return object; 101 | } 102 | 103 | export class Adapter { 104 | 105 | service : DynamoDB; 106 | database : string; 107 | settings : Object; 108 | 109 | constructor(database : string, settings : DynamoDB.DocumentClient.DocumentClientOptions) { 110 | this.database = database, 111 | this.settings = settings; 112 | this.service = new DynamoDB(this.settings); 113 | } 114 | 115 | connect() : Promise { 116 | return Promise.resolve(); 117 | } 118 | 119 | _adaptiveCollection(name : string) : Partition { 120 | return new Partition(this.database, name, this.service); 121 | } 122 | 123 | _schemaCollection() : SchemaPartition { 124 | return new SchemaPartition(this.database, schemaPartition, this.service); 125 | } 126 | 127 | classExists(name : string) : Promise { 128 | return this._schemaCollection().find({ _id : name }).then( 129 | partition => partition.length > 0 130 | ); 131 | } 132 | 133 | setClassLevelPermissions(className, CLPs) : Promise { 134 | return this._schemaCollection().updateSchema(className, { 135 | $set: { _metadata: { class_permissions: CLPs } } 136 | }); 137 | } 138 | 139 | createClass(className, schema) : Promise { 140 | return this.classExists(className).then( 141 | partition => { 142 | if (!partition) { 143 | schema = Transform.convertParseSchemaToMongoSchema(schema); 144 | const mongoObject = Transform.mongoSchemaFromFieldsAndClassNameAndCLP(schema.fields, className, schema.classLevelPermissions); 145 | mongoObject._id = className; 146 | return this._schemaCollection().insertOne(mongoObject) 147 | .then( 148 | result => { 149 | return mongoSchemaToParseSchema(result.ops[0]); 150 | } 151 | ) 152 | .catch( 153 | error => { throw error; } 154 | ) 155 | } else { 156 | throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'Class already exists.'); 157 | } 158 | } 159 | ).catch( 160 | error => { throw error } 161 | ); 162 | } 163 | 164 | addFieldIfNotExists(className, fieldName, type) : Promise { 165 | return this._schemaCollection().addFieldIfNotExists(className, fieldName, type); 166 | } 167 | 168 | deleteClass(className) : Promise { 169 | // only drop Schema! 170 | return this._schemaCollection().findAndDeleteSchema(className); 171 | } 172 | 173 | deleteAllClasses() : Promise { 174 | // only for test 175 | const params = { 176 | AttributeDefinitions: [ 177 | { 178 | AttributeName: "_pk_className", 179 | AttributeType: "S" 180 | }, 181 | { 182 | AttributeName: "_sk_id", 183 | AttributeType: "S" 184 | } 185 | ], 186 | KeySchema: [ 187 | { 188 | AttributeName: "_pk_className", 189 | KeyType: "HASH" 190 | }, 191 | { 192 | AttributeName: "_sk_id", 193 | KeyType: "RANGE" 194 | } 195 | ], 196 | ProvisionedThroughput: { 197 | ReadCapacityUnits: 5, 198 | WriteCapacityUnits: 5 199 | }, 200 | TableName: this.database 201 | }; 202 | 203 | return Cache.flush().then(() => { 204 | return this.service.describeTable({ TableName : this.database }).promise(); 205 | }).then(() => { 206 | return this.service.scan({ TableName : this.database, AttributesToGet: ['_pk_className', '_sk_id'] }).promise(); 207 | }).then((data) => { 208 | if (data.Items.length > 0) { 209 | return Promise.reduce(data.Items, (acc, item) => { 210 | return this.service.deleteItem({ TableName : this.database, Key : item }).promise(); 211 | }); 212 | } else { 213 | return Promise.resolve(); 214 | } 215 | }).then(() => { 216 | return Promise.resolve(); 217 | }).catch((err) => { 218 | Promise.reject(err); 219 | }); 220 | } 221 | 222 | deleteFields(className, schema, fieldNames) : Promise { 223 | // remove fields only from Schema 224 | let update = {}; 225 | fieldNames.forEach(field => { 226 | update[field] = undefined; 227 | }); 228 | 229 | return this._schemaCollection().updateSchema(className, update); 230 | } 231 | 232 | getAllClasses() : Promise { 233 | return this._schemaCollection()._fetchAllSchemasFrom_SCHEMA(); 234 | } 235 | 236 | getClass(className) : Promise { 237 | return this._schemaCollection()._fetchOneSchemaFrom_SCHEMA(className); 238 | } 239 | 240 | transformDateObject(object = {}) : Object { 241 | Object.keys(object).forEach( 242 | key => { 243 | if (object[key] instanceof Date) { 244 | object[key] = object[key].toISOString(); 245 | } 246 | 247 | if (object[key] instanceof Object) { 248 | if (object[key].hasOwnProperty('__type')) { 249 | if ((object[key].__type || "").toLowerCase() == 'date') { 250 | object[key] = new Date(object[key].iso || new Date()); 251 | try { 252 | object[key] = object[key].toISOString(); 253 | } catch(err) { 254 | throw err; 255 | } 256 | } 257 | } else { 258 | object[key] = this.transformDateObject(object[key]); 259 | } 260 | } 261 | } 262 | ) 263 | 264 | return object; 265 | } 266 | 267 | createObject(className, schema, object) : Promise { 268 | object = this.transformDateObject(object); 269 | schema = Transform.convertParseSchemaToMongoSchema(schema); 270 | object = Transform.parseObjectToMongoObjectForCreate(className, object, schema); 271 | object = object = this.transformDateObject(object); 272 | 273 | return this._adaptiveCollection(className).ensureUniqueness(object) 274 | .then(count => { 275 | if (count === 0) { 276 | return this._adaptiveCollection(className).insertOne(object); 277 | } else { 278 | throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'A duplicate value for a field with unique values was provided'); 279 | } 280 | }) 281 | .catch( 282 | error => { throw error } 283 | ); 284 | } 285 | 286 | deleteObjectsByQuery(className, schema, query) : Promise { 287 | schema = Transform.convertParseSchemaToMongoSchema(schema); 288 | query = this.transformDateObject(query); 289 | query = Transform.transformWhere(className, query, schema); 290 | query = this.transformDateObject(query); 291 | 292 | return this._adaptiveCollection(className).deleteMany(query) 293 | .then( 294 | result => { 295 | if (result.n === 0) { 296 | throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); 297 | } 298 | return Promise.resolve(); 299 | } 300 | ) 301 | .catch( 302 | error => { throw error } 303 | ); 304 | } 305 | 306 | updateObjectsByQuery(className, schema, query, update) : Promise { 307 | update = this.transformDateObject(update); 308 | schema = Transform.convertParseSchemaToMongoSchema(schema); 309 | update = Transform.transformUpdate(className, update, schema); 310 | update = this.transformDateObject(update); 311 | query = this.transformDateObject(query); 312 | query = Transform.transformWhere(className, query, schema); 313 | query = this.transformDateObject(query); 314 | 315 | return this._adaptiveCollection(className).ensureUniqueness(update['$set']) 316 | .then(count => { 317 | if (count === 0) { 318 | return this._adaptiveCollection(className).updateMany(query, update); 319 | } else { 320 | throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'A duplicate value for a field with unique values was provided'); 321 | } 322 | }) 323 | .catch( 324 | error => { throw error } 325 | ); 326 | } 327 | 328 | findOneAndUpdate(className, schema, query, update, upsert = false) : Promise { 329 | update = this.transformDateObject(update); 330 | schema = Transform.convertParseSchemaToMongoSchema(schema); 331 | update = Transform.transformUpdate(className, update, schema); 332 | update = this.transformDateObject(update); 333 | query = this.transformDateObject(query); 334 | query = Transform.transformWhere(className, query, schema); 335 | query = this.transformDateObject(query); 336 | 337 | return this._adaptiveCollection(className).ensureUniqueness(update['$set']) 338 | .then(count => { 339 | if (count === 0) { 340 | return this._adaptiveCollection(className).updateOne(query, update, upsert); 341 | } else { 342 | throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'A duplicate value for a field with unique values was provided'); 343 | } 344 | }) 345 | .then(result => Transform.transformToParseObject(className, result.value, schema)) 346 | .catch( 347 | error => { throw error } 348 | ) 349 | } 350 | 351 | upsertOneObject(className, schema, query, update) { 352 | return this.findOneAndUpdate(className, schema, query, update, true); 353 | } 354 | 355 | find(className, schema = {}, query = {}, options : Options = {}) : Promise { 356 | let { skip, limit, sort, keys } = options; 357 | schema = Transform.convertParseSchemaToMongoSchema(schema); 358 | query = this.transformDateObject(query); 359 | query = Transform.transformWhere(className, query, schema); 360 | query = this.transformDateObject(query); 361 | sort = _.mapKeys(sort, (value, fieldName) => Transform.transformKey(className, fieldName, schema)); 362 | keys = _.reduce(keys, (memo, key) => { 363 | memo[Transform.transformKey(className, key, schema)] = 1; 364 | return memo; 365 | }, {}); 366 | 367 | return this._adaptiveCollection(className).find(query, { skip, limit, sort, keys}) 368 | .then( 369 | objects => objects.map(object => Transform.transformToParseObject(className, object, schema)) 370 | ); 371 | } 372 | 373 | _rawFind(className, query = {}) : Promise { 374 | return this._adaptiveCollection(className).find(query) 375 | .catch( 376 | error => { throw error } 377 | ); 378 | } 379 | 380 | ensureUniqueness(className, schema, fieldNames) : Promise { 381 | fieldNames = fieldNames.map(fieldName => Transform.transformKey(className, fieldName, schema)); 382 | 383 | return new Promise( 384 | (resolve, reject) => { 385 | this._adaptiveCollection('_UNIQUE_INDEX_') 386 | .upsertOne( 387 | { _id : className }, 388 | { $set : { fields : fieldNames } } 389 | ).then( 390 | res => { 391 | if (res.value) { 392 | Cache.put('UNIQUE', { [className] : fieldNames }); 393 | resolve(); 394 | } else { 395 | throw new Parse.Error(1, 'DynamoDB cannot create this Index'); 396 | } 397 | } 398 | ).catch( 399 | error => { throw error } 400 | ) 401 | } 402 | ) 403 | 404 | } 405 | 406 | count(className, schema, query) : Promise { 407 | schema = Transform.convertParseSchemaToMongoSchema(schema); 408 | query = this.transformDateObject(query); 409 | query = Transform.transformWhere(className, query, schema); 410 | query = this.transformDateObject(query); 411 | 412 | return this._adaptiveCollection(className).count(query); 413 | } 414 | 415 | performInitialization() { 416 | return Promise.resolve(); 417 | } 418 | 419 | createIndex(className, index) : Promise { 420 | return Promise.resolve(); 421 | } 422 | } -------------------------------------------------------------------------------- /src/Cache.ts: -------------------------------------------------------------------------------- 1 | import * as Promise from 'bluebird'; 2 | import { _ } from 'lodash'; 3 | 4 | // durable cache no ttl! 5 | class Cache { 6 | 7 | private cache : Object = {}; 8 | 9 | constructor() { 10 | 11 | } 12 | 13 | put(key, value, override = false) { 14 | if (this.cache[key] == undefined || override == true) { 15 | this.cache[key] = value; 16 | } 17 | 18 | else if (this.cache[key].constructor === Array) { 19 | if ((value instanceof Array)) value = [value]; 20 | this.cache[key] = _.union(this.cache[key], value); 21 | } 22 | 23 | else if (this.cache[key].constructor === Object) { 24 | this.cache[key] = Object.assign(this.cache[key], value); 25 | } 26 | 27 | return Promise.resolve(this.cache[key]); 28 | } 29 | 30 | get(key, key2 = undefined, key3 = undefined) { 31 | 32 | if (key2 && key3 && this.cache[key] && this.cache[key2]) { 33 | return Promise.resolve(this.cache[key][key2][key3]); 34 | } 35 | 36 | if (key2 && !key3 && this.cache[key]) { 37 | return Promise.resolve(this.cache[key][key2]); 38 | } 39 | 40 | return Promise.resolve(this.cache[key]); 41 | } 42 | 43 | del(key) { 44 | delete this.cache[key]; 45 | return Promise.resolve(true); 46 | } 47 | 48 | flush() : Promise { 49 | this.cache = {}; 50 | return Promise.resolve(true); 51 | } 52 | } 53 | 54 | const _Cache = new Cache(); 55 | 56 | export { 57 | _Cache 58 | } -------------------------------------------------------------------------------- /src/Expression.ts: -------------------------------------------------------------------------------- 1 | import { Parse } from 'parse/node'; 2 | import { $ } from './helpers'; 3 | import { DynamoDB } from 'aws-sdk'; 4 | import { _ } from 'lodash'; 5 | 6 | var u = require('util'); // for debugging; 7 | 8 | const dynamo = new DynamoDB.DocumentClient(); 9 | 10 | // helper class to generate DynamoDB FilterExpression from MongoDB Query Object 11 | export class Expression { 12 | 13 | Expression : string = '[first]'; 14 | ExpressionAttributeValues = {}; 15 | ExpressionAttributeNames = {}; 16 | private _v : string; 17 | 18 | comperators = { 19 | '$gt': '>', 20 | '$lt': '<', 21 | '$gte': '>=', 22 | '$lte': '<=', 23 | '$eq' : '=', 24 | '$ne' : '<>', 25 | '$in' : 'IN', 26 | '$or' : 'OR', 27 | '$and' : 'AND', 28 | '$not' : 'NOT', 29 | '$exists' : '*', 30 | '$regex' : '*', 31 | '$nin' : '*', 32 | '$all' : '*' 33 | } 34 | 35 | __not = { 36 | '$gt': '<', 37 | '$lt': '>', 38 | '$gte': '<=', 39 | '$lte': '>=', 40 | '$eq' : '<>', 41 | '$ne' : '=' 42 | } 43 | 44 | constructor() {} 45 | 46 | isQuery(object : Object = {}) { 47 | let $ = true; 48 | for (let key in object) { 49 | $ = $ && (this.comperators[key] != undefined) 50 | } 51 | return $; 52 | } 53 | 54 | // legacy util, use Expressions intead 55 | static createCondition (comperator : string, value) : DynamoDB.DocumentClient.Condition { 56 | 57 | const DynamoComperator = { 58 | '$gt': 'GT', 59 | '$lt': 'LT', 60 | '$gte': 'GE', 61 | '$lte': 'LE', 62 | '$eq' : 'EQ', 63 | '$ne' : 'NE', 64 | '$in' : 'IN', 65 | '$exists' : 'NOT_NULL', 66 | '$regex' : 'BEGINS_WITH' 67 | } 68 | 69 | let condition : DynamoDB.DocumentClient.Condition = { 70 | ComparisonOperator : DynamoComperator[comperator] || "EQ", 71 | AttributeValueList : [ value ] 72 | } 73 | 74 | if (comperator === '$exists') { 75 | if (value === true) { 76 | condition.ComparisonOperator = "NULL"; 77 | } 78 | delete condition.AttributeValueList; 79 | } 80 | 81 | return condition; 82 | } 83 | 84 | static getDynamoQueryFilter(query : Object = {}) : DynamoDB.DocumentClient.FilterConditionMap { 85 | let QueryFilter : DynamoDB.DocumentClient.FilterConditionMap = {}; 86 | 87 | for (let key in query) { 88 | let cmp = Object.keys(query[key])[0]; 89 | QueryFilter[key] = this.createCondition( 90 | cmp, 91 | query[key][cmp] || query[key] 92 | ) 93 | } 94 | 95 | return QueryFilter; 96 | } 97 | 98 | static getProjectionExpression(keys : string[], _params) : string { 99 | let projection : string[] = []; 100 | 101 | if (!_params.ExpressionAttributeNames) { 102 | _params.ExpressionAttributeNames = {}; 103 | } 104 | 105 | _params.ExpressionAttributeNames['#id'] = '_id'; 106 | _params.ExpressionAttributeNames['#sortId'] = '_sk_id'; 107 | _params.ExpressionAttributeNames['#updated_at'] = '_updated_at'; 108 | _params.ExpressionAttributeNames['#created_at'] = '_created_at'; 109 | 110 | let attributes = Object.keys(_params.ExpressionAttributeNames); 111 | keys.forEach(key => { 112 | if (key) { 113 | const _p = Expression.transformPath(_params, key); 114 | if (keys.length > 0 && projection.indexOf(_p) == -1) { 115 | projection.push(_p); 116 | } 117 | } 118 | }); 119 | 120 | if (projection.indexOf('#id') == -1) projection.push('#id'); 121 | if (projection.indexOf('#sortId') == -1) projection.push('#sortId'); 122 | if (projection.indexOf('#updated_at') == -1) projection.push('#updated_at'); 123 | if (projection.indexOf('#created_at') == -1) projection.push('#created_at'); 124 | return projection.sort().join(', '); 125 | } 126 | 127 | static getUpdateExpression(object : Object, _params, original : Object = {}) : string { 128 | 129 | if (!_params.ExpressionAttributeNames) { 130 | _params.ExpressionAttributeNames = {}; 131 | } 132 | 133 | if (!_params.ExpressionAttributeValues) { 134 | _params.ExpressionAttributeValues = {}; 135 | } 136 | 137 | original = original || {}; 138 | 139 | let $set = {}, $unset = [], $inc = {}, $append = {}, $del = {}; 140 | let _set = [], _unset = [], _del = []; 141 | let exp; 142 | 143 | Object.keys(object || {}).forEach( 144 | _op => { 145 | switch (_op) { 146 | case '$push': 147 | case '$addToSet': 148 | Object.keys(object[_op] || {}).forEach(key => { 149 | let list = []; 150 | if (original[key] instanceof Array) { 151 | list = list.concat(original[key]); 152 | } 153 | if (object[_op][key] instanceof Array) { 154 | list = list.concat(object[_op][key]); 155 | } else { 156 | let o = object[_op][key]; 157 | if (o && o.constructor === Object) { 158 | if (_.intersection(Object.keys(o), ['$slice', '$position']).length > 0) { 159 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB cannot do this operation'); 160 | } else { 161 | if (o.hasOwnProperty('$each') && o['$each'] instanceof Array) { 162 | list = list.concat(o['$each']); 163 | if (o['$sort']) { 164 | let sortable = list.reduce((prev, item) => { 165 | if (item && item.constructor === Object) { 166 | return prev && true; 167 | } else { 168 | return prev && false; 169 | } 170 | }, true); 171 | 172 | if (sortable) { 173 | list = _.orderBy( 174 | list, 175 | Object.keys(o['$sort']), 176 | $.values(o['$sort']).map((k) => { if (k == 1) return 'asc'; else return 'desc' }) 177 | ); 178 | } 179 | } 180 | } 181 | } 182 | } 183 | } 184 | object[_op][key] = _op == '$addToSet' ? _.uniq(list) : list; 185 | }); 186 | $append = object[_op]; 187 | break; 188 | case '$pullAll': 189 | $del = object[_op] || {}; 190 | break; 191 | case '$setOnInsert': 192 | case '$set': 193 | $set = object[_op] || {}; 194 | break; 195 | case '$unset': 196 | $unset = object['$unset'] || {}; 197 | break; 198 | case '$inc': 199 | $inc = object['$inc'] || {}; 200 | break; 201 | case '$currentDate': 202 | for (let key in (object[_op] || {})) { 203 | object[key] = (new Date()).toISOString(); 204 | } 205 | $set = Object.assign($set, object[_op]); 206 | break; 207 | case '$pull': 208 | case '$mul': 209 | case '$min': 210 | case '$max': 211 | case '$rename': 212 | case '$bit': 213 | case '$isolated': 214 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : [' + _op + '] not supported on update'); 215 | default: 216 | $set = object; 217 | break; 218 | } 219 | } 220 | ); 221 | 222 | 223 | delete $set['_id']; 224 | delete $set['_sk_id']; 225 | delete $set['_pk_className']; 226 | 227 | delete $inc['_id']; 228 | delete $inc['_sk_id']; 229 | delete $inc['_pk_className']; 230 | 231 | delete $del['_id']; 232 | delete $del['_sk_id']; 233 | delete $del['_pk_className']; 234 | 235 | delete $unset['_id']; 236 | delete $unset['_sk_id']; 237 | delete $unset['_pk_className']; 238 | 239 | delete $append['_id']; 240 | delete $append['_sk_id']; 241 | delete $append['_pk_className']; 242 | 243 | let attributes = Object.keys(_params.ExpressionAttributeNames || {}); 244 | 245 | Object.keys($set).forEach(path => { 246 | if ($set[path] !== undefined) { 247 | let keys = path.split('.'); 248 | let a = keys[0]; 249 | let value = $set[path]; 250 | if (keys.length > 1) { 251 | _.set(original, path, value); 252 | value = original[a]; 253 | path = a; 254 | } 255 | path = Expression.transformPath(_params, path, value); 256 | let exp = '[key] = [value]'; 257 | exp = exp.replace('[key]', path); 258 | exp = exp.replace('[value]', _params._v); 259 | _set.push(exp); 260 | } else { 261 | if ($unset.indexOf(path) == -1) { 262 | _unset.push(path); 263 | } 264 | } 265 | }); 266 | 267 | Object.keys($inc).forEach(path => { 268 | if (typeof $inc[path] == 'number') { 269 | let exp; 270 | let keys = path.split('.'); 271 | let a = keys[0]; 272 | let value = $inc[path]; 273 | if (keys.length > 1) { 274 | value = _.get(original, path, 0); 275 | if (typeof value == 'number') { 276 | value = $inc[path] + value; 277 | _.set(original, path, value); 278 | path = Expression.transformPath(_params, a, original[a]); 279 | exp = '[key] = [value]'; 280 | exp = exp.replace(/\[key\]/g, path); 281 | exp = exp.replace('[value]', _params._v); 282 | _set.push(exp); 283 | } 284 | } else { 285 | path = Expression.transformPath(_params, path, value); 286 | _params.ExpressionAttributeValues[':__zero__'] = 0; 287 | exp = '[key] = if_not_exists([key],:__zero__) + [value]'; 288 | exp = exp.replace(/\[key\]/g, path); 289 | exp = exp.replace('[value]', _params._v); 290 | _set.push(exp); 291 | } 292 | } 293 | }); 294 | 295 | Object.keys($append).forEach(path => { 296 | if ($append[path] != undefined) { 297 | let exp; 298 | let keys = path.split('.'); 299 | let a = keys[0]; 300 | if (keys.length > 0) { 301 | let list = _.get(original, path, []); 302 | list.push($append[path]); 303 | _.set(original, path, list); 304 | path = Expression.transformPath(_params, a, original[a]); 305 | exp = '[key] = [value]'; 306 | exp = exp.replace(/\[key\]/g, path); 307 | exp = exp.replace('[value]', _params._v); 308 | _set.push(exp); 309 | } else { 310 | path = Expression.transformPath(_params, path, $append[path]); 311 | _params.ExpressionAttributeValues[':__void__'] = []; 312 | exp = '[key] = list_append(if_not_exists([key],:__void__),[value])'; 313 | exp = exp.replace(/\[key\]/g, path); 314 | exp = exp.replace('[value]', _params._v); 315 | _set.push(exp); 316 | } 317 | } 318 | }); 319 | 320 | Object.keys($del).forEach(path => { 321 | if ($del[path] instanceof Array) { 322 | let value = _.get(original, path, []); 323 | if (value instanceof Array) { 324 | $del[path].forEach(item => { 325 | if (item.constructor == Object) { 326 | _.pull(value, _.find(value, item)); 327 | } else { 328 | _.pull(value, item); 329 | } 330 | }); 331 | _.set(original, path, value); 332 | path = path.split('.')[0]; 333 | path = Expression.transformPath(_params, path, original[path]); 334 | let exp = '[key] = [value]'; 335 | exp = exp.replace('[key]', path); 336 | exp = exp.replace('[value]', _params._v); 337 | _set.push(exp); 338 | } 339 | } 340 | }); 341 | 342 | _unset = _unset.concat(Object.keys($unset).map( 343 | key => Expression.transformPath(_params, key) 344 | )); 345 | 346 | if (_set.length > 0) { 347 | if (exp) { 348 | exp = exp + ' SET ' + _set.join(', '); 349 | } else { 350 | exp = 'SET ' + _set.join(', '); 351 | } 352 | } 353 | 354 | if (_unset.length) { 355 | if (exp) { 356 | exp = exp + ' REMOVE ' + _unset.join(', '); 357 | } else { 358 | exp = 'REMOVE ' + _unset.join(', '); 359 | } 360 | } 361 | 362 | delete _params._v; 363 | return exp; 364 | } 365 | 366 | createExpression(key : string, value : any, op, not = false, _all = false) : string { 367 | 368 | if (!op) { 369 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : Operation is not supported'); 370 | } 371 | 372 | let exp : string = ''; 373 | let _key : string = Expression.transformPath(this, key, value); 374 | let _vl = this._v; 375 | 376 | switch (op) { 377 | case 'begins_with': 378 | exp = 'begins_with([key],[value])'; 379 | break; 380 | case 'attribute_exists': 381 | exp = 'attribute_exists([key])'; 382 | delete this.ExpressionAttributeValues[_vl]; 383 | break; 384 | case 'attribute_not_exists': 385 | exp = 'attribute_not_exists([key])'; 386 | delete this.ExpressionAttributeValues[_vl]; 387 | break; 388 | case 'contains': 389 | exp = 'contains([key],[value])'; 390 | break; 391 | case 'IN': 392 | let _v = this.ExpressionAttributeValues[_vl].sort(); 393 | if (_v.indexOf(null) > -1 || _v.indexOf(undefined) > -1) { 394 | if (_v.length == 2) { 395 | this.ExpressionAttributeValues[_vl] = _v[0]; 396 | this.ExpressionAttributeValues[':null'] = null; 397 | exp = '( contains([key],[value]) OR attribute_not_exists([key]) OR [key] = :null )'; 398 | } else { 399 | _v = _v.filter(e => e != null); 400 | let _vs = _v.map( 401 | (e,i) => { 402 | let _k = _vl + '_' + i; 403 | let exp = 'contains([key],[value])'; 404 | this.ExpressionAttributeValues[_k] = e; 405 | exp = exp.replace('[value]', _k); 406 | return exp; 407 | } 408 | ) 409 | delete this.ExpressionAttributeValues[_vl]; 410 | this.ExpressionAttributeValues[':null'] = null; 411 | exp = '( [exp] OR attribute_not_exists([key]) OR [key] = :null )'.replace('[exp]', _vs.join(' OR ')); 412 | } 413 | } else { 414 | _v = _v.filter(e => e != null); 415 | let _vs = _v.map( 416 | (e,i) => { 417 | let _k = _vl + '_' + i; 418 | this.ExpressionAttributeValues[_k] = e; 419 | if (_all) { 420 | let exp = 'contains([key],[value])'; 421 | exp = exp.replace('[value]', _k); 422 | return exp; 423 | } 424 | return _k; 425 | } 426 | ) 427 | delete this.ExpressionAttributeValues[_vl]; 428 | if (_all) { 429 | exp = '( [exp] )'.replace('[exp]', _vs.join(' AND ')); 430 | } else { 431 | exp = '[key] IN ([value])'.replace('[value]', _vs.join()); 432 | } 433 | } 434 | break; 435 | default: 436 | exp = '[key] [op] [value]'; 437 | break; 438 | } 439 | 440 | exp = exp.replace(/\[key\]/g, _key); 441 | exp = exp.replace(/\[value\]/g, _vl); 442 | exp = exp.replace(/\[op\]/g, op); 443 | 444 | if (not) { 445 | exp = 'NOT ( ' + exp + ' )'; 446 | } 447 | 448 | return exp; 449 | } 450 | 451 | // set ExpressionAttributeNames and ExpressionAttributeValues 452 | // and returns the transformed path 453 | // e.g. _id -> #id 454 | // e.g. item.users[1].id -> #item.#users[1].#id 455 | static transformPath(params : any, path : string, value : any = undefined) : string { 456 | 457 | if (!path) { 458 | throw new Error('Key cannot be empty'); 459 | } 460 | 461 | params = params || {}; 462 | 463 | if (!params.hasOwnProperty('ExpressionAttributeNames')) { 464 | params.ExpressionAttributeNames = {} 465 | } 466 | 467 | if ((!params.hasOwnProperty('ExpressionAttributeNames')) && value) { 468 | params.ExpressionAttributeValues = {} 469 | } 470 | 471 | let _key = path.replace(/^(_|\$)+/, ''); 472 | let index = 0, _vl : string; 473 | let keys = path.split('.'); 474 | 475 | let attributes = Object.keys(params.ExpressionAttributeNames); 476 | for (let i=0; i < keys.length; i++) { 477 | let _key = keys[i].replace(/^(_|\$)+/, ''); 478 | _key = _key.toLowerCase(); 479 | let _k = _key.replace(/\[[0-9]+\]/g, ''); 480 | if (attributes.indexOf(_key) == -1) { 481 | // make sure key names don't overlap with each other 482 | if ($.getKey(params.ExpressionAttributeNames, keys[i].replace(/\[[0-9]+\]/g, '')) === null) { 483 | let index = $.count(params.ExpressionAttributeNames, '#' + _k); 484 | if (index > 0) { 485 | _k = _k + '_' + index; 486 | } 487 | params.ExpressionAttributeNames['#' + _k] = keys[i].replace(/\[[0-9]+\]/g, ''); 488 | } 489 | 490 | if (value !== undefined) { 491 | if (i == (keys.length - 1)) { 492 | let index = $.count(params.ExpressionAttributeValues, ':' + _k); 493 | _vl = ':' + _k + '_' + index; 494 | params.ExpressionAttributeValues[_vl] = value; 495 | } 496 | } 497 | } 498 | keys[i] = keys[i].replace(keys[i].replace(/\[[0-9]+\]/g, ''), $.getKey(params.ExpressionAttributeNames, keys[i].replace(/\[[0-9]+\]/g, ''))); 499 | } 500 | 501 | params._v = _vl; 502 | 503 | return keys.join('.'); 504 | } 505 | 506 | build(query = {}, key = null, not = false, _op = null) : Expression { 507 | let exp, _cmp_, size = 0; 508 | Object.keys(query).forEach( 509 | (q,i) => { 510 | 511 | if (i < Object.keys(query).length - 1 && Object.keys(query).length > 1) { 512 | if (_op) { 513 | this.Expression = this.Expression.replace('[first]','( [first] AND [next] )'); 514 | } else { 515 | this.Expression = this.Expression.replace('[first]','[first] AND [next]'); 516 | } 517 | } 518 | 519 | if (i < Object.keys(query).length) { 520 | this.Expression = this.Expression.replace('[next]', '[first]'); 521 | } 522 | 523 | switch(q) { 524 | case '$nor': 525 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : Operator [' + q + '] not supported'); 526 | case '$or': 527 | case '$and': 528 | query[q] = query[q].filter(sq => { 529 | if (sq && sq.constructor === Object && Object.keys(sq).length > 0) { 530 | return sq; 531 | } 532 | }); 533 | query[q].forEach( 534 | (subquery,j) => { 535 | if (j < Object.keys(query[q]).length - 1 && Object.keys(query[q]).length > 1) { 536 | if (_op == '$and') { 537 | this.Expression = this.Expression.replace('[first]','( [first] ' + this.comperators[q] + ' [next] )'); 538 | } else { 539 | this.Expression = this.Expression.replace('[first]','[first] ' + this.comperators[q] + ' [next]'); 540 | } 541 | } 542 | this.build(subquery, key, not, q); 543 | } 544 | ) 545 | break; 546 | case '$eq': 547 | case '$ne': 548 | case '$gt': 549 | case '$lt': 550 | case '$gte': 551 | case '$lte': 552 | _cmp_ = not ? this.__not[q] : this.comperators[q]; 553 | exp = this.createExpression(key, query[q], _cmp_, false); 554 | this.Expression = this.Expression.replace('[first]', exp); 555 | break; 556 | case '$in': 557 | case '$nin': 558 | let _not_; 559 | if (q == '$nin' && not === true) _not_ = false; 560 | if (q == '$nin' && not === false) _not_ = true; 561 | if (q == '$in' && not === true) _not_ = true; 562 | if (q == '$in' && not === false) _not_ = false; 563 | query[q] = query[q] || []; 564 | size = query[q].length; 565 | if (size === 0) query[q] = ['*']; 566 | if (size === 1) query[q] = query[q][0]; 567 | if (size > 100) throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : The [$in] operator is provided with too many operands, ' + size); 568 | _cmp_ = size === 1 ? '=' : 'IN'; 569 | exp = this.createExpression(key, query[q], _cmp_, _not_); 570 | this.Expression = this.Expression.replace('[first]', exp); 571 | break; 572 | case '$regex': 573 | _cmp_ = query[q].startsWith('^') ? 'begins_with' : 'contains'; 574 | query[q] = query[q].replace('^', ''); 575 | query[q] = query[q].replace('\\Q', ''); 576 | query[q] = query[q].replace('\\E', ''); 577 | exp = this.createExpression(key, query[q], _cmp_, not); 578 | this.Expression = this.Expression.replace('[first]', exp); 579 | break; 580 | case '$exists': 581 | _cmp_ = query[q] ? 'attribute_exists' : 'attribute_not_exists'; 582 | exp = this.createExpression(key, query[q], _cmp_, not); 583 | this.Expression = this.Expression.replace('[first]', exp); 584 | break; 585 | case '$not': 586 | this.build(query[q], key, true, _op); 587 | break; 588 | case '$all': 589 | query[q] = (query[q].constructor === Array ? query[q] : []).sort(); 590 | exp = this.createExpression(key, query[q], 'IN', not, true); 591 | this.Expression = this.Expression.replace('[first]', exp); 592 | break; 593 | default: 594 | if (query[q] && query[q].constructor === Object && this.isQuery(query[q])) { 595 | this.build(query[q], q, not, _op); 596 | } else { 597 | if (query[q] === undefined) { 598 | exp = this.createExpression(q, query[q], 'attribute_not_exists', not); 599 | } else if (query[q] === null) { 600 | exp = this.createExpression(q, query[q], '=', not); 601 | } else { 602 | exp = this.createExpression(q, query[q], '=', not); 603 | } 604 | this.Expression = this.Expression.replace('[first]', exp); 605 | } 606 | break; 607 | } 608 | } 609 | ) 610 | 611 | return this; 612 | } 613 | } -------------------------------------------------------------------------------- /src/Partition.ts: -------------------------------------------------------------------------------- 1 | // Partition is the class where objects are stored 2 | // Partition is like Collection in MongoDB 3 | // a Partition is represented by a hash or partition key in DynamoDB 4 | import { DynamoDB } from 'aws-sdk'; 5 | import * as Promise from 'bluebird'; 6 | import { Parse } from 'parse/node'; 7 | import { newObjectId } from 'parse-server/lib/cryptoUtils'; 8 | import { Expression } from './Expression'; 9 | import { _Cache as Cache } from './Cache'; 10 | import { $ } from './helpers'; 11 | import { _ } from 'lodash'; 12 | 13 | var u = require('util'); // for debugging; 14 | 15 | type Options = { 16 | skip? : Object, // not supported 17 | limit? : number, 18 | sort? : Object, // only supported on partition/sort key 19 | keys? : Object 20 | count?: boolean 21 | } 22 | 23 | export class Partition { 24 | database : string; // database is the table name in DynamoDB 25 | className : string; 26 | dynamo : DynamoDB.DocumentClient; 27 | 28 | constructor(database : string, className : string, service : DynamoDB) { 29 | this.dynamo = new DynamoDB.DocumentClient({ service : service }); 30 | this.database = database; 31 | this.className = className; 32 | } 33 | 34 | _get(id : string, keys : string[] = []) : Promise { 35 | keys = keys || []; 36 | let params : DynamoDB.DocumentClient.GetItemInput = { 37 | TableName : this.database, 38 | Key: { 39 | _pk_className : this.className, 40 | _sk_id : id 41 | }, 42 | ConsistentRead : true 43 | } 44 | 45 | if (keys.length > 0) { 46 | params.ProjectionExpression = Expression.getProjectionExpression(keys, params); 47 | } 48 | 49 | return new Promise( 50 | (resolve, reject) => { 51 | this.dynamo.get(params, (err, data) => { 52 | if (err) { 53 | reject(err); 54 | } else { 55 | if (data.Item) { 56 | data.Item._id = data.Item._sk_id; 57 | delete data.Item._pk_className; 58 | delete data.Item._sk_id; 59 | resolve([data.Item]); 60 | } else { 61 | resolve([]); 62 | } 63 | } 64 | }) 65 | } 66 | ); 67 | } 68 | 69 | _query(query: Object = {}, options : Options = {}) : Promise { 70 | //if (Object.keys(query).length > 0) console.log('QUERY', this.className, u.inspect(query, false, null)); 71 | const between = (n, a, b) => { 72 | return (n - a) * (n - b) <= 0 73 | } 74 | 75 | return new Promise( 76 | (resolve, reject) => { 77 | 78 | const _exec = (query: Object = {}, options : Options = {}, params : DynamoDB.DocumentClient.QueryInput = null, results = []) => { 79 | 80 | if (!params) { 81 | let keys = Object.keys(options.keys || {}); 82 | let count = options.count ? true : false; 83 | 84 | // maximum by DynamoDB is 100 or 1MB 85 | let limit; 86 | if (!count) { 87 | limit = options.limit ? options.limit : 100; 88 | } 89 | 90 | // DynamoDB sorts only by sort key (in our case the objectId 91 | options.sort = options.sort || {}; 92 | let descending = false; 93 | if (options.sort.hasOwnProperty('_id') && options.sort['_id'] == -1) { 94 | descending = true; 95 | } 96 | 97 | // Select keys -> projection 98 | let select = keys.length > 0 ? "SPECIFIC_ATTRIBUTES" : "ALL_ATTRIBUTES"; 99 | if (count) { 100 | select = "COUNT" 101 | } 102 | 103 | let _params : DynamoDB.DocumentClient.QueryInput = { 104 | TableName : this.database, 105 | KeyConditionExpression : '#className = :className', 106 | Select : select, 107 | ExpressionAttributeNames : { 108 | '#className' : '_pk_className' 109 | }, 110 | ExpressionAttributeValues : { 111 | ':className' : this.className 112 | }, 113 | ConsistentRead : true 114 | } 115 | 116 | if (!count) { 117 | _params.Limit = limit; 118 | } 119 | 120 | if (Object.keys(query).length > 0) { 121 | 122 | let exp : Expression = new Expression(); 123 | exp = exp.build(query); 124 | if (exp.Expression != '[first]') { 125 | _params.FilterExpression = exp.Expression; 126 | _params.ExpressionAttributeNames = exp.ExpressionAttributeNames; 127 | _params.ExpressionAttributeValues = exp.ExpressionAttributeValues; 128 | _params.ExpressionAttributeNames['#className'] = '_pk_className'; 129 | _params.ExpressionAttributeValues[':className'] = this.className; 130 | } 131 | } 132 | 133 | if (descending) { 134 | _params.ScanIndexForward = descending; 135 | } 136 | 137 | if (keys.length > 0) { 138 | _params.ProjectionExpression = Expression.getProjectionExpression(keys, _params); 139 | } 140 | 141 | params = _params; 142 | } 143 | //if (params.ProjectionExpression) console.log('QUERY EXP', this.className, params.ProjectionExpression, params.ExpressionAttributeNames); 144 | this.dynamo.query(params, (err, data) => { 145 | if (err) { 146 | reject(err); 147 | } else { 148 | results = results.concat(data.Items || []); 149 | if (data.LastEvaluatedKey && (results.length < options.limit)) { 150 | options.limit = options.limit - results.length; 151 | params.ExclusiveStartKey = data.LastEvaluatedKey; 152 | return _exec(query, options, params, results); 153 | } 154 | 155 | if (options.count) { 156 | resolve(data.Count ? data.Count : 0); 157 | } 158 | 159 | results.forEach((item) => { 160 | item._id = item._sk_id; 161 | delete item._pk_className; 162 | delete item._sk_id; 163 | }); 164 | 165 | if (results.length > 1 && Object.keys(options.sort).length > 0) { 166 | results = _.orderBy( 167 | results, 168 | Object.keys(options.sort), 169 | $.values(options.sort).map((k) => { if (k == 1) return 'asc'; else return 'desc' }) 170 | ); 171 | } 172 | //console.log('QUERY RESULT', this.className, u.inspect(results, false, null)) 173 | resolve(results); 174 | } 175 | }); 176 | } 177 | 178 | _exec(query, options); 179 | } 180 | ) 181 | } 182 | 183 | find(query: Object = {}, options : Options = {}) : Promise { 184 | let id = query['_id']; 185 | if (id && typeof id === 'string' && !(query.hasOwnProperty('_rperm') || query.hasOwnProperty('acl'))) { 186 | let _keys = options.keys || {}; 187 | let keys = Object.keys(_keys); 188 | return this._get(id, keys); 189 | } 190 | return this._query(query, options); 191 | } 192 | 193 | count(query: Object = {}, options : Options = {}) : Promise { 194 | options.count = true; 195 | return this._query(query, options); 196 | } 197 | 198 | ensureUniqueness(object) : Promise { 199 | if (Object.keys(object || {}).length > 0 && Cache.get('UNIQUE')) { 200 | return Cache.get('UNIQUE', this.className).then(value => { 201 | if (value) { 202 | return Promise.resolve(value); 203 | } else { 204 | return this.relaodUniques(); 205 | } 206 | }).then(uniques => { 207 | if (uniques.length > 0) { 208 | uniques = _.intersection(uniques, Object.keys(object)); 209 | if (uniques.length > 0) { 210 | return this.count({ 211 | $or : uniques.map(key => { 212 | return { [key] : object[key] } 213 | }) 214 | }); 215 | } else { 216 | return Promise.resolve(0); 217 | } 218 | } else { 219 | return Promise.resolve(0); 220 | } 221 | }).catch(error => { 222 | throw error 223 | }); 224 | } else { 225 | return Promise.resolve(0); 226 | } 227 | } 228 | 229 | relaodUniques() { 230 | let params : DynamoDB.DocumentClient.GetItemInput = { 231 | TableName : this.database, 232 | Key: { 233 | _pk_className : '_UNIQUE_INDEX_', 234 | _sk_id : this.className 235 | }, 236 | ConsistentRead : true 237 | } 238 | 239 | return this.dynamo.get(params).promise().then( 240 | item => { 241 | let uniques = []; 242 | if (item && item['fields']) { 243 | Cache.put('UNIQUE', { [this.className] : item['fields'] }); 244 | uniques = item['fields']; 245 | } else { 246 | Cache.put('UNIQUE', { [this.className] : [] }); 247 | } 248 | 249 | return Promise.resolve(uniques); 250 | } 251 | ); 252 | } 253 | 254 | insertOne(object) : Promise { 255 | let id = object['_id'] || newObjectId(); 256 | object['_id'] = id; 257 | 258 | let params : DynamoDB.DocumentClient.PutItemInput = { 259 | TableName : this.database, 260 | Item: { 261 | _pk_className : this.className, 262 | _sk_id : id, 263 | ...object 264 | }, 265 | ExpressionAttributeNames : { 266 | '#id' : '_sk_id', 267 | }, 268 | ConditionExpression : 'attribute_not_exists(#id)', 269 | } 270 | 271 | return new Promise( 272 | (resolve, reject) => { 273 | this.dynamo.put(params, (err, data) => { 274 | if (err) { 275 | if (err.name == 'ConditionalCheckFailedException') { 276 | reject(new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'Class already exists.')); 277 | } else { 278 | reject(err); 279 | } 280 | } else { 281 | resolve({ ok : 1, n : 1, ops : [ object ], insertedId : id }); 282 | } 283 | }); 284 | } 285 | ) 286 | } 287 | 288 | // update in DynamoDB is upsert by default but if used with ConditionExpression, it will fail 289 | // if upsert is true, try to find the item 290 | updateOne(query = {}, object : Object, upsert = false) : Promise { 291 | //console.log('UPDATE', query, object); 292 | let id = query['_id']; 293 | 294 | let params : DynamoDB.DocumentClient.UpdateItemInput = { 295 | TableName : this.database, 296 | Key: { 297 | _pk_className : this.className 298 | }, 299 | ReturnValues : 'ALL_NEW' 300 | } 301 | 302 | let find = Promise.resolve(); 303 | 304 | if (id) { 305 | if (typeof id == 'string') { 306 | find = this._get(id).then( 307 | result => { 308 | if (result.length > 0 && result[0]._id === id) { 309 | return result[0]; 310 | } 311 | return null; 312 | } 313 | ); 314 | } else { 315 | return this.updateMany(query, object, upsert); 316 | } 317 | } else { 318 | if (Object.keys(query).length > 0) { 319 | find = this.find(query, { limit : 1 }).then( 320 | results => { 321 | if (results.length > 0 && results[0]._id) { 322 | return results[0]; 323 | } 324 | return null; 325 | } 326 | ) 327 | } else { 328 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : you must specify query keys'); 329 | } 330 | } 331 | 332 | let exp : Expression = new Expression(); 333 | exp = exp.build(query); 334 | params.ConditionExpression = exp.Expression; 335 | params.ExpressionAttributeNames = exp.ExpressionAttributeNames; 336 | params.ExpressionAttributeValues = exp.ExpressionAttributeValues; 337 | 338 | return new Promise( 339 | (resolve, reject) => { 340 | find.then((result) => { 341 | if (result && result._id) { 342 | params.UpdateExpression = Expression.getUpdateExpression(object, params, result); 343 | params.Key._sk_id = result._id; 344 | //console.log('UPDATE PARAMS', params); 345 | this.dynamo.update(params, (err, data) => { 346 | if (err) { 347 | if (err.name == 'ConditionalCheckFailedException') { 348 | if (upsert) { 349 | reject(err); 350 | } else { 351 | resolve({ ok : 1, n : 0, nModified : 0, value : null}); 352 | } 353 | } else { 354 | reject(err); 355 | } 356 | } else { 357 | if (data && data.Attributes) { 358 | data.Attributes._id = data.Attributes._sk_id; 359 | delete data.Attributes._pk_className; 360 | delete data.Attributes._sk_id; 361 | resolve({ ok : 1, n : 1, nModified : 1, value : data.Attributes }); 362 | } else { 363 | resolve({ ok : 1, n : 1, nModified : 1, value : null }); 364 | } 365 | } 366 | }); 367 | } else { 368 | // here we do upserting 369 | if (upsert) { 370 | object = { 371 | ...object['$set'], 372 | ...object['$inc'] 373 | } 374 | object['_id'] = newObjectId(); 375 | this.insertOne(object).then( 376 | res => resolve({ ok : 1, n : 1, nModified : 1, value : res.ops[0] }) 377 | ); 378 | } else { 379 | resolve({ ok : 1, n : 1, nModified : 1, value : null }); 380 | } 381 | } 382 | }); 383 | } 384 | ) 385 | } 386 | 387 | upsertOne(query = {}, object : Object) : Promise { 388 | return this.updateOne(query, object, true); 389 | } 390 | 391 | updateMany(query = {}, object, upsert = false) : Promise { 392 | let id = query['_id']; 393 | 394 | if (typeof id == 'string') { 395 | return this.updateOne(query, object); 396 | } else { 397 | let options = { 398 | keys : { _id : 1 } 399 | } 400 | 401 | return this.find(query, options).then( 402 | (res) => { 403 | res = res.filter(item => item._id != undefined); 404 | if (res.length === 0) throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : cannot update nothing'); 405 | 406 | let promises = res.map( 407 | item => this.updateOne({ _id : item._id }, object, upsert) 408 | ); 409 | 410 | return new Promise( 411 | (resolve, reject) => { 412 | Promise.all(promises).then( 413 | res => { 414 | res = res.filter(item => item.value != undefined); 415 | if (res.length > 0) { 416 | resolve(res); 417 | } else { 418 | resolve(null); 419 | } 420 | } 421 | ).catch( 422 | err => reject(err) 423 | ); 424 | } 425 | ) 426 | } 427 | ) 428 | } 429 | } 430 | 431 | deleteOne(query = {}) : Promise { 432 | let id = query['_id']; 433 | let params : DynamoDB.DocumentClient.DeleteItemInput = { 434 | TableName : this.database, 435 | Key: { 436 | _pk_className : this.className 437 | } 438 | } 439 | 440 | let find = Promise.resolve(); 441 | 442 | if (id) { 443 | find = Promise.resolve(id); 444 | } else { 445 | if (Object.keys(query).length > 0) { 446 | find = this.find(query, { limit : 1 }).then( 447 | results => { 448 | if (results.length > 0 && results[0]._id) { 449 | return results[0]._id; 450 | } else { 451 | return -1; 452 | } 453 | } 454 | ) 455 | } else { 456 | throw new Parse.Error(Parse.Error.INVALID_QUERY, 'DynamoDB : you must specify query keys'); 457 | } 458 | } 459 | 460 | let exp : Expression = new Expression(); 461 | exp = exp.build(query); 462 | params.ConditionExpression = exp.Expression; 463 | params.ExpressionAttributeNames = exp.ExpressionAttributeNames; 464 | params.ExpressionAttributeValues = exp.ExpressionAttributeValues; 465 | 466 | return new Promise( 467 | (resolve, reject) => { 468 | find.then((id) => { 469 | if (id == -1) { 470 | reject(); 471 | } else { 472 | params.Key._sk_id = id; 473 | this.dynamo.delete(params, (err, data) => { 474 | if (err) { 475 | if (err.name == 'ConditionalCheckFailedException') { 476 | resolve({ ok : 1, n : 0, deletedCount : 0 }); 477 | } else { 478 | reject(err); 479 | } 480 | } else { 481 | resolve({ ok : 1, n : 1, deletedCount : 1 }); 482 | } 483 | }); 484 | } 485 | }); 486 | } 487 | ) 488 | } 489 | 490 | deleteMany(query = {}) : Promise { 491 | let id = query['_id']; 492 | if (id) { 493 | return this.deleteOne(query); 494 | } else { 495 | let options = { 496 | limit : 25, 497 | keys : { _id : 1 } 498 | } 499 | 500 | return this.find(query, options).then( 501 | (res) => { 502 | res = res.filter(item => item._id != undefined); 503 | if (res.length === 0) throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found'); 504 | 505 | let promises = res.map( 506 | item => this.deleteOne({ _id : item._id }) 507 | ); 508 | 509 | return new Promise( 510 | (resolve, reject) => { 511 | Promise.all(promises).then( 512 | res => resolve({ ok : 1, n : res.length, deletedCount : res.length }) 513 | ).catch( 514 | () => reject(new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'DynamoDB : Internal Error')) 515 | ); 516 | } 517 | ) 518 | } 519 | ) 520 | } 521 | } 522 | 523 | _ensureSparseUniqueIndexInBackground(indexRequest) : Promise { 524 | return Promise.resolve(); 525 | } 526 | 527 | drop () : Promise { 528 | return Promise.resolve(); 529 | } 530 | } -------------------------------------------------------------------------------- /src/SchemaPartition.ts: -------------------------------------------------------------------------------- 1 | // mocking parse-server/src/Adapters/Storage/Mongo/MongoSchemaCollection.js 2 | import * as Promise from 'bluebird'; 3 | import { Partition } from './Partition'; 4 | import * as MongoTransform from 'parse-server/lib/Adapters/Storage/Mongo/MongoTransform'; 5 | 6 | const nonFieldSchemaKeys = ['_id', '_metadata', '_client_permissions']; 7 | 8 | const emptyCLPS = Object.freeze({ 9 | find: {}, 10 | get: {}, 11 | create: {}, 12 | update: {}, 13 | delete: {}, 14 | addField: {}, 15 | }); 16 | 17 | const defaultCLPS = Object.freeze({ 18 | find: {'*': true}, 19 | get: {'*': true}, 20 | create: {'*': true}, 21 | update: {'*': true}, 22 | delete: {'*': true}, 23 | addField: {'*': true}, 24 | }); 25 | 26 | type sType = { type, targetClass? } 27 | 28 | export function mongoFieldToParseSchemaField(type) { 29 | if (type[0] === '*') { 30 | return { 31 | type: 'Pointer', 32 | targetClass: type.slice(1), 33 | }; 34 | } 35 | if (type.startsWith('relation<')) { 36 | return { 37 | type: 'Relation', 38 | targetClass: type.slice('relation<'.length, type.length - 1), 39 | }; 40 | } 41 | switch (type) { 42 | case 'number': return {type: 'Number'}; 43 | case 'string': return {type: 'String'}; 44 | case 'boolean': return {type: 'Boolean'}; 45 | case 'date': return {type: 'Date'}; 46 | case 'map': 47 | case 'object': return {type: 'Object'}; 48 | case 'array': return {type: 'Array'}; 49 | case 'geopoint': return {type: 'GeoPoint'}; 50 | case 'file': return {type: 'File'}; 51 | case 'bytes': return {type: 'Bytes'}; 52 | } 53 | } 54 | 55 | export function mongoSchemaFieldsToParseSchemaFields(schema) { 56 | var fieldNames = Object.keys(schema).filter(key => nonFieldSchemaKeys.indexOf(key) === -1); 57 | var response = fieldNames.reduce((obj, fieldName) => { 58 | obj[fieldName] = mongoFieldToParseSchemaField(schema[fieldName]) 59 | return obj; 60 | }, {}); 61 | response['ACL'] = {type: 'ACL'}; 62 | response['createdAt'] = {type: 'Date'}; 63 | response['updatedAt'] = {type: 'Date'}; 64 | response['objectId'] = {type: 'String'}; 65 | return response; 66 | } 67 | 68 | export function mongoSchemaToParseSchema(mongoSchema) { 69 | let clps = defaultCLPS; 70 | if (mongoSchema._metadata && mongoSchema._metadata.class_permissions) { 71 | clps = {...emptyCLPS, ...mongoSchema._metadata.class_permissions}; 72 | } 73 | return { 74 | className: mongoSchema._id, 75 | fields: mongoSchemaFieldsToParseSchemaFields(mongoSchema), 76 | classLevelPermissions: clps, 77 | }; 78 | } 79 | 80 | export function _mongoSchemaQueryFromNameQuery(name : string, query = {}) : Object { 81 | const object = { _id: name }; 82 | if (query) { 83 | Object.keys(query).forEach(key => { 84 | object[key] = query[key]; 85 | }); 86 | } 87 | return object; 88 | } 89 | 90 | export function parseFieldTypeToMongoFieldType({ type, targetClass = null }) { 91 | switch (type) { 92 | case 'Pointer': return `*${targetClass}`; 93 | case 'Relation': return `relation<${targetClass}>`; 94 | case 'Number': return 'number'; 95 | case 'String': return 'string'; 96 | case 'Boolean': return 'boolean'; 97 | case 'Date': return 'date'; 98 | case 'Object': return 'object'; 99 | case 'Array': return 'array'; 100 | case 'GeoPoint': return 'geopoint'; 101 | case 'File': return 'file'; 102 | case 'Bytes': return 'bytes'; 103 | } 104 | } 105 | 106 | export class SchemaPartition extends Partition { 107 | 108 | _fetchAllSchemasFrom_SCHEMA() { 109 | return this.find().then( 110 | schemas => schemas.map(mongoSchemaToParseSchema) 111 | ).catch( 112 | error => { throw error } 113 | ); 114 | } 115 | 116 | _fetchOneSchemaFrom_SCHEMA(name: string) : Promise { 117 | let query = _mongoSchemaQueryFromNameQuery(name); 118 | 119 | return this.find(query, { limit: 1 }).then( 120 | result => { 121 | if (result.length === 1) { 122 | return mongoSchemaToParseSchema(result[0]); 123 | } else { 124 | throw undefined; 125 | } 126 | } 127 | ); 128 | } 129 | 130 | findAndDeleteSchema(name : string) : Promise { 131 | return this.deleteOne({ _id : name }); 132 | } 133 | 134 | updateSchema(name: string, update: Object) : Promise { 135 | let _query = _mongoSchemaQueryFromNameQuery(name); 136 | return this.updateOne(_mongoSchemaQueryFromNameQuery(name), update); 137 | } 138 | 139 | upsertSchema(name: string, query: Object, update: Object) : Promise { 140 | return this.upsertOne(_mongoSchemaQueryFromNameQuery(name, query), update); 141 | } 142 | 143 | addFieldIfNotExists(className: string, fieldName: string, type: sType) : Promise { 144 | return this.upsertSchema( 145 | className, 146 | { [fieldName]: { '$exists': false } }, 147 | { '$set' : { [fieldName]: parseFieldTypeToMongoFieldType(type) } } 148 | ); 149 | } 150 | } -------------------------------------------------------------------------------- /src/helpers.ts: -------------------------------------------------------------------------------- 1 | export class $ extends Object { 2 | static values (obj : Object) { 3 | return Object.keys(obj).map(e => obj[e]); 4 | } 5 | 6 | static count (obj : Object, s : string) { 7 | return Object.keys(obj).filter(e => { if (e.indexOf(s) === 0) return e }).length; 8 | } 9 | 10 | static getKey(obj : Object, v : any) { 11 | for (let k in obj) { 12 | if (obj[k] === v) return k; 13 | } 14 | 15 | return null; 16 | } 17 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Partition } from './Partition'; 2 | import { Expression } from './Expression'; 3 | import { Adapter } from './Adapter'; 4 | 5 | export class DynamoDB { 6 | 7 | Partition; 8 | Expression; 9 | 10 | Adapter : Adapter; 11 | 12 | constructor(readonly database, readonly settings) { 13 | this.database = database; 14 | this.settings = settings; 15 | this.Partition = Partition; 16 | this.Expression = Expression; 17 | } 18 | 19 | getAdapter() { 20 | if (this.Adapter) { 21 | return this.Adapter 22 | } 23 | 24 | this.Adapter = new Adapter(this.database, this.settings); 25 | return this.Adapter; 26 | } 27 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "noImplicitAny": false, 6 | "sourceMap": false, 7 | "outDir": "build", 8 | "experimentalDecorators": true, 9 | "moduleResolution": "node" 10 | }, 11 | 12 | "include": [ 13 | "src/**/*.ts", 14 | "spec/**/*.ts" 15 | ], 16 | 17 | "exclude": [ 18 | "node_modules" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "express": "registry:dt/express#4.0.0+20170118060322", 4 | "express-serve-static-core": "registry:dt/express-serve-static-core#4.0.0+20170324160323", 5 | "mime": "registry:dt/mime#0.0.0+20160428043022", 6 | "serve-static": "registry:dt/serve-static#1.7.1+20161128184045" 7 | }, 8 | "globalDependencies": { 9 | "es6-shim": "registry:dt/es6-shim#0.31.2+20160726072212", 10 | "node": "registry:dt/node#7.0.0+20170322231424" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /vendors/aws-dynamodb-truncate/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Applexus Labs 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 all 13 | 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 THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendors/aws-dynamodb-truncate/README.md: -------------------------------------------------------------------------------- 1 | # aws-dynamodb-truncate 2 | 3 | a clone of https://github.com/ApplexusLabs/aws-dynamodb-truncate 4 | -------------------------------------------------------------------------------- /vendors/aws-dynamodb-truncate/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-dynamodb-truncate", 3 | "version": "1.0.0", 4 | "description": "Simple script to delete all records in a DynamoDB table", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "dependencies": { 10 | "aws-sdk": "latest", 11 | "async":"latest" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/ApplexusLabs/aws-dynamodb-truncate.git" 16 | }, 17 | "author": "", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/ApplexusLabs/aws-dynamodb-truncate/issues" 21 | }, 22 | "homepage": "https://github.com/ApplexusLabs/aws-dynamodb-truncate#readme", 23 | "jshintConfig": { 24 | "bitwise": true, 25 | "browser": true, 26 | "camelcase": true, 27 | "curly": true, 28 | "eqeqeq": true, 29 | "es5": true, 30 | "esnext": true, 31 | "immed": true, 32 | "indent": 2, 33 | "jasmine": true, 34 | "latedef": false, 35 | "newcap": true, 36 | "noarg": true, 37 | "node": true, 38 | "quotmark": "single", 39 | "regexp": true, 40 | "smarttabs": true, 41 | "strict": true, 42 | "trailing": false, 43 | "undef": true, 44 | "unused": true, 45 | "white": false, 46 | "globals": {} 47 | } 48 | } 49 | --------------------------------------------------------------------------------