├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public ├── App.js ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg ├── models ├── index.d.ts ├── index.js ├── schema.d.ts └── schema.js └── serviceWorker.js /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # amplify 4 | amplify 5 | .graphqlconfig.yml 6 | .amplifyrc 7 | **/graphql/ 8 | **/aws-exports.js 9 | 10 | # dependencies 11 | /node_modules 12 | /.pnp 13 | .pnp.js 14 | 15 | # testing 16 | /coverage 17 | 18 | # production 19 | /build 20 | 21 | # misc 22 | .DS_Store 23 | .env.local 24 | .env.development.local 25 | .env.test.local 26 | .env.production.local 27 | 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Amplify Datastore - JS 2 | 3 | This is the sample code to illustrate the AWS News Blog post : [Amplify Datastore - Simplify Development of Offline Apps with GraphQL](https://aws.amazon.com/blogs/aws/amplify-datastore-simplify-development-of-offline-apps-with-graphql) 4 | 5 | ## Prerequisite: 6 | 7 | Install Amplify CLI 8 | 9 | ```sh 10 | npm i -g @aws-amplify/cli 11 | ``` 12 | 13 | ## Create a new react app 14 | 15 | ```sh 16 | npx create-react-app amplify-datastore --use-npm 17 | ``` 18 | 19 | ```sh 20 | cd amplify-datastore 21 | ``` 22 | 23 | ## Add DataStore to your app 24 | 25 | Add support for datastore, it creates the API for you (there is no need to type `amplify add api` after this) 26 | 27 | ```sh 28 | npx amplify-app 29 | ``` 30 | 31 | ## Add our GraphQL schema 32 | 33 | ```sh 34 | echo "enum PostStatus { 35 | ACTIVE 36 | INACTIVE 37 | } 38 | 39 | type Post @model { 40 | id: ID! 41 | title: String! 42 | comments: [Comment] @connection(name: \"PostComments\") 43 | rating: Int! 44 | status: PostStatus! 45 | } 46 | type Comment @model { 47 | id: ID! 48 | content: String 49 | post: Post @connection(name: \"PostComments\") 50 | }" > amplify/backend/api/amplifyDatasource/schema.graphql 51 | ``` 52 | 53 | ## Add dependencies 54 | 55 | ```sh 56 | npm i @aws-amplify/core @aws-amplify/datastore 57 | ``` 58 | 59 | ## Run modelgen 60 | 61 | Model-Gen generates code to implement language specific model classes. 62 | 63 | ```sh 64 | npm run amplify-modelgen 65 | ``` 66 | 67 | At this stage, you can already use the app in standalone mode. No AWS Account is required. 68 | 69 | ## Create the cloud-based backend 70 | 71 | ```sh 72 | npm run amplify-push 73 | ``` 74 | 75 | ## Implement & Start the App 76 | 77 | ```sh 78 | # download a simple react app 79 | curl -o src/App.js https://raw.githubusercontent.com/sebsto/amplify-datastore-js-e2e/master/src/App.js 80 | 81 | # start the app 82 | npm run start 83 | ``` 84 | 85 | ## Cleanup 86 | 87 | At the end of your test, you can delete the backend infrastructure 88 | 89 | ```sh 90 | amplify delete 91 | ``` 92 | 93 | You might need to manually delete two Amazon S3 buckets created. 94 | In the [AWS Console](https://s3.console.aws.amazon.com/s3/home), search for the two buckets having `datastore` part of their name. 95 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "amplify-datastore-js-e2e", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@aws-amplify/datastore": "^2.0.9", 7 | "react": "^16.13.1", 8 | "react-dom": "^16.13.1", 9 | "react-scripts": "3.2.0" 10 | }, 11 | "scripts": { 12 | "start": "react-scripts start", 13 | "build": "react-scripts build", 14 | "test": "react-scripts test", 15 | "eject": "react-scripts eject", 16 | "amplify-modelgen": "node amplify/scripts/amplify-modelgen.js", 17 | "amplify-push": "node amplify/scripts/amplify-push.js" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "ini": "^1.3.5" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /public/App.js: -------------------------------------------------------------------------------- 1 | ../src/App.js -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sebsto/amplify-datastore-js-e2e/c41de7984d93ab0d8b7fad5d89ad8ca4f1568deb/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sebsto/amplify-datastore-js-e2e/c41de7984d93ab0d8b7fad5d89ad8ca4f1568deb/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sebsto/amplify-datastore-js-e2e/c41de7984d93ab0d8b7fad5d89ad8ca4f1568deb/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | } 8 | 9 | .App-header { 10 | background-color: #282c34; 11 | min-height: 100vh; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | justify-content: center; 16 | font-size: calc(10px + 2vmin); 17 | color: white; 18 | } 19 | 20 | .App-link { 21 | color: #09d3ac; 22 | } 23 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import logo from "./logo.svg"; 3 | import "./App.css"; 4 | 5 | import Amplify from "@aws-amplify/core"; 6 | import { DataStore, Predicates } from "@aws-amplify/datastore"; 7 | 8 | import { Post, PostStatus } from "./models"; 9 | 10 | import awsConfig from "./aws-exports"; 11 | Amplify.configure(awsConfig); 12 | 13 | function onCreate() { 14 | DataStore.save( 15 | new Post({ 16 | title: `New title ${Date.now()}`, 17 | rating: (function getRandomInt(min, max) { 18 | min = Math.ceil(min); 19 | max = Math.floor(max); 20 | return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive 21 | })(1, 7), 22 | status: PostStatus.ACTIVE 23 | }) 24 | ); 25 | } 26 | 27 | function onDeleteAll() { 28 | DataStore.delete(Post, Predicates.ALL); 29 | } 30 | 31 | async function onQuery(setPosts) { 32 | const posts = await DataStore.query(Post, c => c.rating("gt", 4)); 33 | setPosts(posts) 34 | } 35 | 36 | async function listPosts(setPosts) { 37 | const posts = await DataStore.query(Post, Predicates.ALL); 38 | setPosts(posts); 39 | } 40 | 41 | function App() { 42 | 43 | const [posts, setPosts] = useState([]); 44 | 45 | useEffect( () => { 46 | 47 | listPosts(setPosts); 48 | 49 | const subscription = DataStore.observe(Post).subscribe(msg => { 50 | console.log(msg.model, msg.opType, msg.element); 51 | listPosts(setPosts); 52 | }); 53 | 54 | const handleConnectionChange = () => { 55 | const condition = navigator.onLine ? 'online' : 'offline'; 56 | console.log(condition); 57 | if (condition === 'online') { listPosts(setPosts); } 58 | } 59 | 60 | window.addEventListener('online', handleConnectionChange); 61 | window.addEventListener('offline', handleConnectionChange); 62 | 63 | return () => subscription.unsubscribe(); 64 | }, []); 65 | 66 | return ( 67 |
68 |
69 | logo 70 |
71 | { onCreate(); listPosts(setPosts)} } /> 72 | { onDeleteAll(); listPosts(setPosts)} } /> 73 | { onQuery(setPosts)} } /> 74 | { listPosts(setPosts)} } /> 75 |
76 | 77 | 78 | 79 | 80 | 81 | {posts.map( (item,i) => { 82 | return 83 | } )} 84 | 85 |
IdTitleRatingVersion
{posts[i].id.substring(0,8)}...{posts[i].title}{posts[i].rating}{posts[i]._version}
86 | Download source code 87 |
88 |
89 | ); 90 | } 91 | 92 | export default App; 93 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/models/index.d.ts: -------------------------------------------------------------------------------- 1 | import { ModelInit, MutableModel, PersistentModelConstructor } from "@aws-amplify/datastore"; 2 | 3 | export enum PostStatus { 4 | ACTIVE = "ACTIVE", 5 | INACTIVE = "INACTIVE" 6 | } 7 | 8 | export declare class Post { 9 | readonly id: string; 10 | readonly title: string; 11 | readonly comments?: Comment; 12 | readonly rating: number; 13 | readonly status: PostStatus | keyof typeof PostStatus; 14 | constructor(init: ModelInit); 15 | static copyOf(source: Post, mutator: (draft: MutableModel) => MutableModel | void): Post; 16 | } 17 | 18 | export declare class Comment { 19 | readonly id: string; 20 | readonly content?: string; 21 | readonly post?: Post; 22 | constructor(init: ModelInit); 23 | static copyOf(source: Comment, mutator: (draft: MutableModel) => MutableModel | void): Comment; 24 | } -------------------------------------------------------------------------------- /src/models/index.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import { initSchema } from '@aws-amplify/datastore'; 3 | import { schema } from './schema'; 4 | 5 | const PostStatus = { 6 | "ACTIVE": "ACTIVE", 7 | "INACTIVE": "INACTIVE" 8 | }; 9 | 10 | const { Post, Comment } = initSchema(schema); 11 | 12 | export { 13 | Post, 14 | Comment, 15 | PostStatus 16 | }; -------------------------------------------------------------------------------- /src/models/schema.d.ts: -------------------------------------------------------------------------------- 1 | import { Schema } from '@aws-amplify/datastore'; 2 | 3 | export declare const schema: Schema; -------------------------------------------------------------------------------- /src/models/schema.js: -------------------------------------------------------------------------------- 1 | export const schema = { 2 | "models": { 3 | "Post": { 4 | "syncable": true, 5 | "name": "Post", 6 | "attributes": [ 7 | { 8 | "type": "model", 9 | "properties": {} 10 | } 11 | ], 12 | "fields": { 13 | "id": { 14 | "name": "id", 15 | "targetName": "id", 16 | "isArray": false, 17 | "type": "ID", 18 | "isRequired": true, 19 | "attributes": [] 20 | }, 21 | "title": { 22 | "name": "title", 23 | "targetName": "title", 24 | "isArray": false, 25 | "type": "String", 26 | "isRequired": true, 27 | "attributes": [] 28 | }, 29 | "comments": { 30 | "name": "comments", 31 | "targetName": "comments", 32 | "isArray": true, 33 | "type": { 34 | "model": "Comment" 35 | }, 36 | "isRequired": false, 37 | "attributes": [ 38 | { 39 | "type": "connection", 40 | "properties": { 41 | "name": "PostComments" 42 | } 43 | } 44 | ] 45 | }, 46 | "rating": { 47 | "name": "rating", 48 | "targetName": "rating", 49 | "isArray": false, 50 | "type": "Int", 51 | "isRequired": true, 52 | "attributes": [] 53 | }, 54 | "status": { 55 | "name": "status", 56 | "targetName": "status", 57 | "isArray": false, 58 | "type": { 59 | "enum": "PostStatus" 60 | }, 61 | "isRequired": true, 62 | "attributes": [] 63 | } 64 | } 65 | }, 66 | "Comment": { 67 | "syncable": true, 68 | "name": "Comment", 69 | "attributes": [ 70 | { 71 | "type": "model", 72 | "properties": {} 73 | } 74 | ], 75 | "fields": { 76 | "id": { 77 | "name": "id", 78 | "targetName": "id", 79 | "isArray": false, 80 | "type": "ID", 81 | "isRequired": true, 82 | "attributes": [] 83 | }, 84 | "content": { 85 | "name": "content", 86 | "targetName": "content", 87 | "isArray": false, 88 | "type": "String", 89 | "isRequired": false, 90 | "attributes": [] 91 | }, 92 | "post": { 93 | "name": "post", 94 | "targetName": "post", 95 | "isArray": false, 96 | "type": { 97 | "model": "Post" 98 | }, 99 | "isRequired": false, 100 | "attributes": [ 101 | { 102 | "type": "connection", 103 | "properties": { 104 | "name": "PostComments" 105 | } 106 | } 107 | ] 108 | } 109 | } 110 | } 111 | }, 112 | "enums": { 113 | "PostStatus": { 114 | "name": "PostStatus", 115 | "values": [ 116 | "ACTIVE", 117 | "INACTIVE" 118 | ] 119 | } 120 | }, 121 | "version": "6f6cb16389ad6c2218ecfcd0914c25ea" 122 | }; -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------