投稿時間:2023-03-20 02:15:07 RSSフィード2023-03-20 02:00 分まとめ(17件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS lambdaタグが付けられた新着投稿 - Qiita SlackBOTからAWS Lamdbaを動かし、Slackに通知する(NodeJS) https://qiita.com/WalrusEarl/items/4a9258d51b4e0f8b4ab1 awslamdba 2023-03-20 01:13:46
python Pythonタグが付けられた新着投稿 - Qiita abc294の備忘録(Python) https://qiita.com/BoldogHos/items/a7995c06662fb73913ba atcoder 2023-03-20 01:32:16
python Pythonタグが付けられた新着投稿 - Qiita ウルヴァリンのように自己修復するPythonスクリプト https://qiita.com/kazuma_1_00/items/8555d48bccefce206cef wolverine 2023-03-20 01:19:06
python Pythonタグが付けられた新着投稿 - Qiita Flaskによるflashメッセージの体験 https://qiita.com/yu__programming/items/dd0cdc38982b752d45b9 flash 2023-03-20 01:11:58
AWS AWSタグが付けられた新着投稿 - Qiita 驚くべき完成度!AWSでサーバレスAPIの作成をChatGPTに頼んだ結果〜AWSエンジニアの役割が変化する?!〜 https://qiita.com/takuma818t/items/ff89ed5ba7c41ae7f2e5 chatgpt 2023-03-20 01:36:23
AWS AWSタグが付けられた新着投稿 - Qiita AWS IoT Twinmakerを使って、複数データをまとめて管理してみる① https://qiita.com/hirarin-142131/items/9600fb5e2813ec69e1f4 awsiot 2023-03-20 01:12:26
海外TECH MakeUseOf How to Clear and Delete WhatsApp Chats https://www.makeuseof.com/how-to-clear-delete-whatsapp-chats/ whatsapp 2023-03-19 16:45:17
海外TECH MakeUseOf How to Use the RPG Notes App for Android to Improve Your Tabletop RPGs https://www.makeuseof.com/how-to-use-the-rpg-notes-app-on-android/ android 2023-03-19 16:30:16
海外TECH MakeUseOf How to Batch Convert HEIC Images to JPEG Format in Windows 10 & 11 https://www.makeuseof.com/batch-convert-heic-images-jpeg-windows/ windows 2023-03-19 16:15:17
海外TECH DEV Community Building a Secure Database-Centric OpenAPI in 15 Minutes https://dev.to/zenstack/building-a-secure-database-centric-openapi-in-15-minutes-36oj Building a Secure Database Centric OpenAPI in MinutesIf you are a developer familiar with RESTful APIs you might have heard of OpenAPI It is a specification for describing RESTful APIs in a format readable for humans and machines Building a public facing OpenAPI includes three tasks Authoring an OpenAPI specification which serves as the contract between the API provider and the API consumer Implementing the API endpoints based on the specification Optionally implementing client SDKs for consuming the API In this post you ll see how to accomplish all these tasks and build a database centric OpenAPI service secure and documented within minutes You can find the finished project here ScenarioI will use a simple Pet Store API as an example to facilitate easier understanding The API will have the following resources User who can signup login and order pets Pet which can be listed and ordered by users Order which is created by users and contains a list of pets Business rules Anonymous users can sign up and log in Anonymous users can list unsold pets Authenticated users can list unsold pets and pets ordered by them Authenticated users can create orders for unsold pets Authenticated users can view their orders Building it upWe ll use Express js as the framework for building the service However other frameworks like Fastify can be used as well and the general process is similar Creating the projectLet s first create a new Express js project with Typescript mkdir express petstorecd express petstorenpm init ynpm install expressnpm install D typescript tsx types node types expressnpx tsc initCreate the service entrance point code app ts with the following content app tsimport express from express const app express enable JSON body parserapp use express json app get req res gt res send Hello World app listen gt console log Server ready at http localhost Start the server npx tsx watch app tsNow in a new shell window hit the service endpoint and verify it works curl localhost Hello World Modeling dataData modeling is the most crucial part of building a resource centric API In this guide we ll use Prisma and ZenStack to model the database Prisma is a toolkit that offers a declarative data modeling experience and ZenStack is a power pack to Prisma providing enhancements like access control specification generation automatic service generation and many other improvements Let s first initialize our project for data modeling npm install D prismanpm install prisma clientnpx zenstack latest initThe zenstack CLI installs Prisma and other dependencies and creates a boilerplate schema zmodel file Update it with the following content to reflect our requirements schema zmodeldatasource db provider sqlite url file petstore db generator client provider prisma client js model User id String id default cuid email String unique password String orders Order model Pet id String id default cuid createdAt DateTime default now updatedAt DateTime updatedAt name String category String order Order relation fields orderId references id orderId String model Order id String id default cuid createdAt DateTime default now updatedAt DateTime updatedAt pets Pet user User relation fields userId references id userId String Run the following command to generate Prisma schema and push it to the database npx zenstack generatenpx prisma db pushAlso create a prisma seed ts file that populates the database with some data Then when you reset your local database you can rerun the script to fill in the data prisma seed tsimport PrismaClient Prisma from prisma client const prisma new PrismaClient const petData Prisma PetCreateInput id luna name Luna category kitten id max name Max category doggie id cooper name Cooper category reptile async function main console log Start seeding for const p of petData const pet await prisma pet create data p console log Created Pet with id pet id console log Seeding finished main then async gt await prisma disconnect catch async e gt console error e await prisma disconnect process exit Run the script to seed our database npx tsx prisma seed ts Implementing the APIZenStack dramatically simplifies the development of database centric APIs by providing a built in RESTful implementation You can use a framework specific adapter to install the RESTful services into your application Let s see how to do it with Express js npm install zenstackhq serverThe integration with Express js is achieved by the ZenStackMiddleware middleware factory Use it to mount the RESTful APIs at the path of your choice The getPrisma callback is used to get a Prisma client instance for the current request For now we ll just return the global Prisma client app tsimport PrismaClient from prisma client import ZenStackMiddleware from zenstackhq server express import express from express const app express app use express json const prisma new PrismaClient app use api ZenStackMiddleware getPrisma gt prisma app listen gt console log Server ready at http localhost With these few lines of code you ve got CRUD APIs running for all resources User Pet and Order Test it by fetching all pets curl localhost api pet findMany id luna createdAt T Z updatedAt T Z name Luna category kitten id max createdAt T Z updatedAt T Z name Max category doggie id cooper createdAt T Z updatedAt T Z name Cooper category reptile Easy isn t it The automatically generated APIs have mapping to Prisma client methods findMany findUnique create update aggregate etc They also have the same structure as PrismaClient for input arguments and responses For POST and PUT requests the input args are sent directly as the request body application json For GET and DELETE requests the input args is JSON serialized and sent as the q query parameters url encoded For example you can get a filtered list of pets by curl http localhost api pet findMany q B where A B category A doggie D D URL is encoded from http localhost api pet findMany q where category doggie id max createdAt T Z updatedAt T Z name Max category doggie Our API is up and running but it has one big problem it s not guarded by any security measures Anybody can read and update any data Let s fix that in the following sections in two steps authentication and authorization Adding authenticationFor this simple service we ll adopt an email password based authentication and issue a JWT token for each successful login Let s first look at the signup part Since the User resource already has a CRUD API we don t need to implement a separate API for signup since signup is just creating a User The only thing that we need to take care of is to make sure we store hashed passwords instead of plain text Achieving this is simple just add a password attribute to the password field ZenStack will automatically hash the field before storing it in the database Note that we also added the omit attribute to mark password field to be dropped from the response since we don t want it ever to be returned to the client schema prismamodel User id String id default cuid email String unique password String password omit orders Order Login requires verification of credentials and we need to implement it manually Install several new dependencies npm install bcryptjs jsonwebtoken dotenvnpm install D types jsonwebtokenCreate a env file under the root and put a JWT SECRET environment variable in it You should always use a strong secret in production JWT SECRET abcAdd the api login route as the following app tsimport dotenv from dotenv import jwt from jsonwebtoken import compareSync from bcryptjs load env environment variablesdotenv config app post api login async req res gt const email password req body const user await prisma user findFirst where email if user compareSync password user password res status json error Invalid credentials else sign a JWT token and return it in the response const token jwt sign sub user id process env JWT SECRET res json id user id email user email token Finally change the getPrisma callback in the ZenStackMiddleware to an enhanced Prisma client returned by the withPresets call so that the password and omit attributes can take effect app tsimport withPresets from zenstackhq runtime app use api ZenStackMiddleware getPrisma gt withPresets prisma Beware that with the enhanced Prisma client all CRUD operations are denied by default unless you open them up explicitly Let s open up the create and read operations for User to support the signup login flow schema prismamodel User id String id default cuid email String unique password String password omit orders Order everybody can signup allow create true user profile is publicly readable allow read true Now regenerate Prisma schema and push the changes to the database npx zenstack generate amp amp npx prisma db pushRestart the dev server and we can test out our signup login flow Sign up a user curl X POST localhost api user create H Content Type application json d data email tom pet inc password abc id clfanlysvhtktutornel email tom pet inc Login curl X POST localhost api login H Content Type application json d email tom pet inc password abc id clfanlysvhtktutornel email tom pet inc token Adding authorizationNow that we have authentication in place we can add access control rules to our schema to secure our CRUD service Make the following changes to the Pet and Order models schema prismamodel Pet id String id default cuid createdAt DateTime default now updatedAt DateTime updatedAt name String category String order Order relation fields orderId references id orderId String unsold pets are readable to all sold ones are readable to buyers only allow read orderId null order user auth only allow update to orderId field if it s not set yet unsold allow update name future name amp amp category future category amp amp orderId null model Order id String id default cuid createdAt DateTime default now updatedAt DateTime updatedAt pets Pet user User relation fields userId references id userId String users can read their orders allow read create auth user The syntax for allow and deny is pretty self explanatory A few things to note The auth function returns the currently authenticated user You ll see how it s hooked up shortly The future function returns the entity value after an update is applied The second allow rule on the Pet model looks a bit complex It s needed because we want to disallow creating orders that include sold pets On the database level it means that the orderId field of Pet can only be updated if it s null meaning it s not sold yet We also used the future function to disallow updates to other fields You can learn more about access policies here By declaratively defining access policies in the schema you don t need to implement these rules in your API anymore It s easier to ensure consistency making the schema a single source of truth for your data s shape and security rules There s one piece still missing though we need to hook the authenticated user identity into the system so that the auth function works To do that we require the API callers to carry the JWT token as a bearer token in the Authorization header Then on the server side we extract it from the current request and pass it to the withPresets call as the context Add a getUser helper to decode the user from the token and pass that to the withPresets call app tsimport type Request from express function getUser req Request const token req headers authorization split console log TOKEN token if token return undefined try const decoded any jwt verify token process env JWT SECRET return id decoded sub catch bad token return undefined app use api ZenStackMiddleware getPrisma req gt return withPresets prisma user getUser req Now the policy engine has access to the authenticated user and can enforce the authorization rules Rerun code generation and restart the dev server Now let s test out the authorization npx zenstack generate amp amp npx prisma db push Testing out authorizationLogin to get a token curl X POST localhost api login H Content Type application json d email tom pet inc password abc id lt user id gt email tom pet inc token lt token gt Store the returned user id and token in environment variables for future use userId lt user id gt token lt token gt Create an order Place an order for the Luna cat Note that we pass the token in the Authorization header curl X POST localhost api order create H Content Type application json H Authorization Bearer token d data userId userId pets connect id luna id clfapaykzvhwrsdl createdAt T Z updatedAt T Z userId clfanlysvhtktutornel List pets anonymously Luna is gone now because it s sold curl localhost api pet findMany id clfamyjpvhqlngay createdAt T Z updatedAt T Z name Max category doggie id clfamyjpavhqluyslf createdAt T Z updatedAt T Z name Cooper category reptile List pets with credentials Luna is visible again with an orderId on it because the user who makes an order can read pets in it curl localhost api pet findMany H Authorization Bearer token id clfamyjpvhqlhko createdAt T Z updatedAt T Z name Luna category kitten orderId clfapaykzvhwrsdl id clfamyjpvhqlngay createdAt T Z updatedAt T Z name Max category doggie id clfamyjpavhqluyslf createdAt T Z updatedAt T Z name Cooper category reptile Creating an order for Luna again will result in an error curl X POST localhost api order create H Content Type application json H Authorization Bearer token d data userId userId pets connect id luna prisma true rejectedByPolicy true code P message denied by policy Pet entities failed update check entity failed policy check You can continue testing with the Order model and see if its behavior conforms to the access policies Generating OpenAPI specificationSo far we ve implemented a secure REST like API It doesn t fully conform to RESTful API s resource oriented API endpoint design but it fully preserves Prisma s data query flexibility To call it an OpenAPI we have to offer a formal specification Fortunately ZenStack can generate OpenAPI V specifications for you You only need to turn on the plugin in your schema npm install D zenstackhq openapi schema prismaplugin openapi provider zenstackhq openapi prefix api title Pet Store API version description My awesome pet store API output petstore api json When you run zenstack generate it will generate a petstore api json file for you You can serve it to your API consumer with tools like Swagger UI npx zenstack generateThere is a caveat though remember we manually implemented the api login endpoint ZenStack doesn t know that and the generated JSON spec doesn t include it However we can use some extra tooling to fix that First install some new dependencies npm install swagger ui express express jsdoc swaggernpm install D types swagger ui expressThen add JSDoc for specifying its input and output to the api login route app ts Login input typedef object LoginInput property string email required The email property string password required The password Login response typedef object LoginResponse property string id required The user id property string email required The user email property string token required The access token POST api login tags user param LoginInput request body required input return LoginResponse login response app post api login async req res gt The JSDoc attaches OpenAPI metadata to the api login route We can then use express jsdoc swagger and swagger ui express to merge these two fragments of API specification and server a Swagger UI for it app tsimport expressJSDocSwagger from express jsdoc swagger load the CRUD API spec from the JSON file generated by zenstack const crudApiSpec require petstore api json options for loading the extra OpenAPI from JSDocconst swaggerOptions info version title Pet Store API filesPattern app ts scan app ts for OpenAPI JSDoc baseDir dirname exposeApiDocs true apiDocsPath v api docs serve the merged JSON specifcation at v api docs merge two specs and serve the UIexpressJSDocSwagger app swaggerOptions crudApiSpec Now if you hit http localhost api docs you ll see the API documentation UI You can also access the raw JSON spec at http localhost v api docs Generating Client SDKGreat We ve got a running service with a formal specification Now the consumers can implement clients to talk to it using any HTTP client With the OpenAPI specification we can take one more step to generate a strong typed client SDK for them In this sample we ll achive it using openapi typescript and openapi typescript fetch npm install D openapi typescript types node fetchnpm install node fetch openapi typescript fetchnpx openapi typescript http localhost v api docs output client types tsWe can then use the generated types to do strongly typed API calls for both input and output Create a client ts to try it out client tsimport fetch Headers Request Response from node fetch import Fetcher from openapi typescript fetch import paths from client types polyfill fetch for nodeif globalThis fetch globalThis fetch fetch as any globalThis Headers Headers as any globalThis Request Request as any globalThis Response Response as any async function main const fetcher Fetcher for lt paths gt fetcher configure baseUrl http localhost const login fetcher path api login method post create const data loginResult await login email tom pet inc password abc loginResult is typed as id string email string token string console log Login result JSON stringify loginResult undefined const token loginResult token get orders together with their pets const getOrders fetcher path api order findMany method get create const data orders await getOrders q JSON stringify include pets true headers Authorization Bearer token console log Orders JSON stringify orders undefined main You can run it with npx tsx client ts Wrap upBuilding a database centric OpenAPI service involves many tasks designing the data model authoring the specification implementing the service and generating the client SDK But as you can see it doesn t need to be hard and time consuming The key takeaway is that if you can use a single source of truth to represent your data schema and access rules many other artifacts can be generated from it It saves your precious time from writing boilerplate code and also makes it much easier to keep everything in sync along the way The finished project can be found here P S We re building ZenStack a toolkit that supercharges Prisma ORM with a powerful access control layer and unleashes its full potential for full stack development 2023-03-19 16:07:35
海外TECH DEV Community [Discussion] Future of Writing https://dev.to/itsrakesh/discussion-future-of-writing-2onm Discussion Future of WritingWhen I first tried ChatGPT I immediately got these thoughts in my head What will be the future of writing Will people still read my articles ChatGPT can explain better than me and a lot more Now with recent launch of GPT it became even more advanced I am aware that it is not perfect at the moment because it lacks access to information from the real world and often makes mistakes but it will eventually get much better So what do you think is the Future of writing Please share your opinions thoughts questions in the comments 2023-03-19 16:06:39
ニュース BBC News - Home SNP leadership: SNP in 'tremendous mess', interim chief says https://www.bbc.co.uk/news/uk-scotland-scotland-politics-65001543?at_medium=RSS&at_campaign=KARANGA party 2023-03-19 16:02:47
ニュース BBC News - Home Arsenal 4-1 Crystal Palace: Gunners go eight points clear at top of Premier League https://www.bbc.co.uk/sport/football/64929886?at_medium=RSS&at_campaign=KARANGA Arsenal Crystal Palace Gunners go eight points clear at top of Premier LeagueArsenal move eight points clear at the top of the Premier League thanks to a routine home victory over managerless Crystal Palace 2023-03-19 16:07:47
ニュース BBC News - Home Brighton 5-0 Grimsby Town: Seagulls safely through to FA Cup semi-final https://www.bbc.co.uk/sport/football/64984194?at_medium=RSS&at_campaign=KARANGA Brighton Grimsby Town Seagulls safely through to FA Cup semi finalEvan Ferguson scores twice to send Brighton through to their third FA Cup semi final and end Grimsby Town s dream run at the Amex Stadium 2023-03-19 16:37:38
ニュース BBC News - Home FA Cup semi-finals: Manchester City to face Sheffield United, Brighton to play Manchester United or Fulham https://www.bbc.co.uk/sport/football/65008407?at_medium=RSS&at_campaign=KARANGA FA Cup semi finals Manchester City to face Sheffield United Brighton to play Manchester United or FulhamManchester City will face Championship side Sheffield United in the FA Cup semi finals while Brighton will play Manchester United or Fulham 2023-03-19 16:46:16
ビジネス ダイヤモンド・オンライン - 新着記事 年をとってみないとわからない、長生きの意外なメリットとは? - 長寿脳──120歳まで健康に生きる方法 https://diamond.jp/articles/-/319713 年をとってみないとわからない、長生きの意外なメリットとは長寿脳ー歳まで健康に生きる方法【最新の認知症治療を実践する脳のカリスマが年超の長寿研究から導いた幸せな生き方】年代には大ベストセラー『歳までボケないの方法脳とこころのアンチエイジング』で歳ブームを巻き起こした医学博士・白澤卓二医師渾身の自信作『長寿脳ー歳まで健康に生きる方法』が完成。 2023-03-20 01:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 親世代と子世代で違う関西の最新大学事情とは? - 大学図鑑!2024 有名大学82校のすべてがわかる! https://diamond.jp/articles/-/319656 関西 2023-03-20 01:50:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)