尝试使用Amplify + AppSync + Cognito来测试读写控制
假设有一个使用Amplify和Cognito用户池,通过AppSync+GraphQL管理内容的系统。
要尝试的事项
-
- amplifyで構築したシステムにてCognitoユーザープールにて認証の管理
- 認証されたユーザー毎に投稿や、閲覧できるコンテンツを制御する
索引
-
- 初期構築
-
- example実装
- readとwriteの権限を制御
首先进行初始建设。
关于安装Amplify的CLI,请参考上述内容,从create-react-app开始编写。
$ npx create-react-app react-amplified
$ cd react-amplified
$ amplify init
? Enter a name for the project reactamplified
? Enter a name for the environment dev
? Choose your default editor: Vim (via Terminal, Mac OS only)
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path: src
? Distribution Directory Path: build
? Build Command: npm run-script build
? Start Command: npm run-script start
这里大致是默认设置。
接下来执行“add auth”和“add api”。
选择使用GraphQL的API,例如选择“博客”与“帖子”以及“评论”。
$ amplify add auth
Do you want to use the default authentication and security configuration? Default configuration
Warning: you will not be able to edit these selections.
How do you want users to be able to sign in? Username
Do you want to configure advanced settings? No, I am done.
$ amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: reactamplified
? Choose the default authorization type for the API Amazon Cognito User Pool
Use a Cognito user pool configured as a part of this project.
? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Do you want a guided schema creation? Yes
? What best describes your project: One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
? Do you want to edit the schema now? Yes
$ amplify push
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
schima.graphQL默认会变成这样
type Blog @model ) {
id: ID!
name: String!
posts: [Post] @connection(keyName: "byBlog", fields: ["id"])
}
type Post @model @key(name: "byBlog", fields: ["blogID"])) {
id: ID!
title: String!
blogID: ID!
blog: Blog @connection(fields: ["blogID"])
comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}
type Comment @model @key(name: "byPost", fields: ["postID", "content"]) {
id: ID!
postID: ID!
post: Post @connection(fields: ["postID"])
content: String!
}
试着使用mock吧。
我使用WSL2上的Ubuntu,但是我没有安装Java,所以我也要运行apt-get命令。
$ sudo apt-get install default-jre
$ amplify mock
GraphQL schema compiled successfully.
Edit your schema at /mnt/c/Users/masra/react-amplified/amplify/backend/api/reactamplified/schema.graphql or place .graphql files in a directory at /mnt/c/Users/masra/react-amplified/amplify/backend/api/reactamplified/schema
Running GraphQL codegen
✔ Generated GraphQL operations successfully and saved at src/graphql
AppSync Mock endpoint is running at http://192.168.x.1:20002
有什么东西站了起来。
![reactop.png](https://cdn.silicloud.com/blog-img/blog/img/657d81f7913a08637a6ae8e9/16-0.png)
选择突变会使得创建成为可能。
举例完成
然后,我尝试找到使用这个博客模式的样本时,发现了下面这个网站似乎很有参考价值。感觉像是工作坊时候的那种,暂时先试试这个吧。
https://amplify-workshop.go-aws.com/40_graphql/10_setting_up_appsync.html 的Github地址如下。
需要更改Album应用的schema吗?一旦修改完毕,执行amplify push。
type Album
@model
@auth(rules: [{allow: owner}]) {
id: ID!
name: String!
photos: [Photo] @connection(keyName: "byAlbum", fields: ["id"])
}
type Photo
@model
@key(name: "byAlbum", fields: ["albumId"], queryField: "listPhotosByAlbum")
@auth(rules: [{allow: owner}]) {
id: ID!
albumId: ID!
album: Album @connection(fields: ["albumId"])
bucket: String!
fullsize: PhotoS3Info!
thumbnail: PhotoS3Info!
}
type PhotoS3Info {
key: String!
width: Int!
height: Int!
}
amplify push
然后,在模拟UI上执行以下操作。就像创建两个相册的感觉。
mutation {
createAlbum(input:{name:"First Album"}) {
id
name
}
}
mutation {
createAlbum(input:{name:"Second Album"}) {
id
name
}
}
接下来要重写App.js。
点击位于页面上方的 “Replace src/App.js with this content” 的按钮,可以复制源代码。
(在这个阶段,)通过AppSync获取并显示已注册的Album列表,并且具备通过createAlbum添加新Album的功能。
$ vi src/App.js
$ npm install --save aws-amplify react-router-dom @aws-amplify/api aws-amplify-react semantic-ui-react
$ npm run build
> react-amplified@0.1.0 build /mnt/c/Users/masra/react-amplified
> react-scripts build
Creating an optimized production build...
Failed to compile.
./src/App.js
Attempted import error: 'createAlbum' is not exported from './graphql/mutations' (imported as 'mutations').
然后执行 $ npm run start!
![reactop2.png](https://cdn.silicloud.com/blog-img/blog/img/657d81f7913a08637a6ae8e9/30-0.png)
某种CSS和其他内容似乎无法加载,但总体功能是正常的。
可能是因为没有注册“从模拟中发布的第一张专辑”或者拥有者不同。
看起来可以通过模拟的“更新授权”登录,然后使用“测试用户”从模拟中创建第五张专辑。
![reactop2.png](https://cdn.silicloud.com/blog-img/blog/img/657d81f7913a08637a6ae8e9/32-0.png)
当使用 TestUser 登录时,内容将顺利显示出来。
![reactop3.png](https://cdn.silicloud.com/blog-img/blog/img/657d81f7913a08637a6ae8e9/34-0.png)
我试了一下创建一个名为TestUser2的账户并尝试登录,但是我的相册是空的。@auth正常工作。
工作坊的计划似乎是在继续增加存储空间的同时上传照片,但我想要尝试的是 @auth ,所以达到了目的。
…不过,也可以试一试读取权限和写入权限。
控制读取和写入权限
这里整理了一些参考资料。
这次,我觉得拥有者或私人都可以。
这样可以吗?
type Album
type Album
@model
@auth(rules: [
{ allow: owner },
{ allow: private, operations: [read] }
])
{
id: ID!
name: String!
photos: [Photo] @connection(keyName: "byAlbum", fields: ["id"])
}
type Photo
@model
@key(name: "byAlbum", fields: ["albumId"], queryField: "listPhotosByAlbum")
@auth(rules: [
{ allow: owner },
{ allow: private, operations: [read] }
])
{
id: ID!
albumId: ID!
album: Album @connection(fields: ["albumId"])
bucket: String!
fullsize: PhotoS3Info!
thumbnail: PhotoS3Info!
}
type PhotoS3Info {
key: String!
width: Int!
height: Int!
}
然后推送。
$ amplify codegen
$ amplify push
$ npm run start
太棒了!
![reactop4.png](https://cdn.silicloud.com/blog-img/blog/img/657d81f7913a08637a6ae8e9/45-0.png)
起初,只是进行了代码生成,为什么没有反映出来呢?我很慌乱,后来才发现是因为应用程序引用了从后端推送过来的内容。。
不要忘记这个。
$ amplify delete