投稿時間:2023-02-16 18:15:05 RSSフィード2023-02-16 18:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia Mobile] iOSとAndroidに「十分な競争圧力が働いていない」と公取委が指摘する理由 法整備もある? https://www.itmedia.co.jp/mobile/articles/2302/16/news157.html android 2023-02-16 17:07:00
AWS AWS Japan Blog BitcoinとEthereumのオープンデータセットにアクセスしてクロスチェーン分析を行う https://aws.amazon.com/jp/blogs/news/access-bitcoin-and-ethereum-open-datasets-for-cross-chain-analytics/ sreejigopal 2023-02-16 08:26:40
python Pythonタグが付けられた新着投稿 - Qiita mysql5.7でjson用カラムをdataclassesで形式を固定する https://qiita.com/alingogo/items/88583a171fb3590d9ea9 dataclasse 2023-02-16 17:40:54
python Pythonタグが付けられた新着投稿 - Qiita Python3.7系 をM1 Macで動かす https://qiita.com/mount-tyo/items/871488705f0b0cc29b17 guidemmac 2023-02-16 17:21:32
python Pythonタグが付けられた新着投稿 - Qiita Pythonでお手軽MultiSet! https://qiita.com/reatoretch/items/d8e58ecd62b608e82f09 multiset 2023-02-16 17:12:13
Linux Ubuntuタグが付けられた新着投稿 - Qiita Pythonで32bitfloatのwavファイルを再生する https://qiita.com/hotstaff/items/9c886e86cec42663b3f5 bitfloat 2023-02-16 17:35:17
技術ブログ Developers.IO AWS Organizationsでマルチアカウント戦略を始めよう【ウェビナー資料公開】 https://dev.classmethod.jp/articles/aws-organizations-webinar-2023-02-08/ awsorganizations 2023-02-16 08:51:47
技術ブログ Developers.IO [レポート]Streamlitで拡がるデータクラウド #SnowflakeDB #SnowdayJapan https://dev.classmethod.jp/articles/snowday-japan-streamlit-expands-data-cloud/ snowdayjapan 2023-02-16 08:05:44
海外TECH DEV Community #refineweek: Adding CRUD Actions and Authentication https://dev.to/refine/refineweek-adding-crud-actions-and-authentication-1j1k refineweek Adding CRUD Actions and AuthenticationIn this post we build on our existing understanding of dataProvider and authProvider props of lt Refine gt to implement CRUD operations in our Pixels app that we initialized in the previous post While doing so we discuss the roles of lt Refine gt component s resources and routerProvider props as well CRUD actions are supported by the Supabase data provider we chose for our project and in this post we use them to build a public gallery of canvases We implement creation and displaying of individual canvases as well as drawing on them We also add authentication features supported by the supabaseClient we discussed on Day Two of the refineWeek series This is Day Three and refineWeek is a seven part tutorial that aims to help developers learn the ins and outs of refine s powerful capabilities and get going with refine within a week refineWeek seriesDay Pilot amp refine architectureDay Setting Up the Client App OverviewIn the last episode we explored refine s auth and data providers in significant detail We saw that lt Refine gt s dataProvider and authProvider props were set to support Supabase thanks to the pankod refine supabase package We mentioned that dataProvider methods allow us to communicate with API endpoints and authProvider methods help us with authentication and authorization We are able to access and invoke these methods from consumer components via their corresponding hooks In this post we will be leveraging Supabase dataProvider methods to implement CRUD operations for a canvases resource We are going to start by adding canvases as a resource on which we will be able to perform create show and list actions We will first work on a public gallery that lists all canvases and a dashboard page that shows a selection of featured canvases by implementing the the list action We will allow users to perform the canvas create action from a modal Then we will also implement the show action for a canvas We will then apply Supabase auth provider to allow only logged in users to carry out create actions on canvases and pixels On the way we will explore how refine does the heavylifting under the hood for us with React Query and its own set of providers and hooks making CRUD operations implementation a breeze But before we start we have to set up Supabase with our database tables and get the access credentials Setting Up Supabase for RefineFor this app we are using a PostgreSQL database for our backend Our database will be hosted in the Supabase cloud In order to set up a PostgreSQL server we need to sign up with Supabase first After signing up and logging in to a developer account we have to complete the following steps Create a PostgreSQL server with an appropriate name Create necessary tables in the database and add relationships Get API keys provided by Supabase for the server and set up supabaseClient inside our refine project Below we go over these steps one by one Creating a PostgreSQL Server with SupabaseCreating a database server is quite intutive in Supabase Just go over to your organization s dashboard and start doing something For me I have initialized a server with the name refine pixels under a free tier If you need a quick hand please follow this quickstart guide Adding Tables to a Supabase DatabaseFor our app we have four tables auth users public users canvases and pixels The entity relational diagram for our database looks like this We have a fifth logs table which we are going to use for audit logging with the auditLogProvider on Day Seven However as we are progressing step by step we are not concerned with that at the moment We will be adding the logs table on its day In order to add the above tables to your Supabase database please follow the below instructions auth users TableThe auth users table is concerned with authentication in our app It is created by Supabase as part of its authentication module so we don t need to do anything about it Supabase supports a myriad of third party authentication providers as well as user input based email password authentication In our app we ll implement GitHub authentication besides the email password based option public users TableSupabase doesn t allow a client to query the auth users table for security reasons So we need to create a shadow of the auth users table in public users with additional columns We need this shadow table to be able to query user information such as avatar url and roles from this table So in order to create the pubic users table go ahead and run this SQL script in the SQL Editor of your Supabase project dashboard Create a table for public userscreate table users id uuid references auth users not null primary key updated at timestamp with time zone username text unique full name text avatar url text This trigger automatically creates a public users entry when a new user signs up via Supabase Auth See using triggers for more details create or replace function public handle new public user returns trigger as begin insert into public users id full name avatar url values new id new raw user meta data gt gt full name new raw user meta data gt gt avatar url return new end language plpgsql security definer create trigger on auth user created after insert on auth users for each row execute procedure public handle new public user Set up Storage insert into storage buckets id name values avatars avatars Set up access controls for storage See policy examples for more details create policy Avatar images are publicly accessible on storage objects for select using bucket id avatars create policy Anyone can upload an avatar on storage objects for insert with check bucket id avatars canvases TableFor the canvases table run this SQL script inside the Supabase SQL Editor create table canvases id text unique primary key not null user id uuid references users on delete cascade not null name text not null width int not null height int not null is featured boolean default false not null created at timestamp with time zone default timezone utc text now not null updated at timestamp with time zone default timezone utc text now not null pixels TableFor the pixels table run the following SQL script create table pixels id int generated by default as identity primary key not null user id uuid references users on delete cascade not null canvas id text references canvases on delete cascade not null x int not null y int not null color text not null created at timestamp with time zone default timezone utc text now not null If you want to create the tables using Table Editor from the dashboard feel free to use the Supabase docs Relationship Between TablesIf we look closely public users table has a one to many relationship with canvases and a canvas must belong to a user Similarly canvases also has a one to many relationship with pixels A canvas has many pixels and a pixel must belong to a canvas Also public users has a one to many relationship with pixels Disable RLSFor simplicity we ll disable Row Level Security Set Up supabaseClient for lt Refine gt ProvidersNow it s time to use the Supabase hosted database server inside our refine app First we need to get the access credentials for our server from the Supabase dashboard We can avail them by following this section in the Supabase quickstart guide I recommend storing these credentials in a env file envSUPABASE URL YOUR SUPABASE URLSUPABASE KEY YOUR SUPABASE KEYDoing so will let us use these credentials to update the supabaseClient ts file created by refine at initialization supabaseClient tsimport createClient from pankod refine supabase const SUPABASE URL process env SUPABASE URL const SUPABASE KEY process env SUPABASE KEY export const supabaseClient createClient SUPABASE URL SUPABASE KEY lt Refine gt component s dataProvider authProvider and liveProvider objects utilize this supabaseClient to connect to the PostgreSQL server hosted on Supabase With this set up now we can introduce canvases resource and start implementing CRUD operations for our app so that we can perform queries on the canvases table lt Refine gt s resources PropIf we look at our initial App tsx component it looks like this App tsximport React from react import Refine from pankod refine core import AuthPage notificationProvider ReadyPage ErrorComponent from pankod refine antd import dataProvider liveProvider from pankod refine supabase import routerProvider from pankod refine react router v import supabaseClient from utility import authProvider from authProvider function App return lt Refine dataProvider dataProvider supabaseClient liveProvider liveProvider supabaseClient authProvider authProvider routerProvider routerProvider routes path register element lt AuthPage type register gt path forgot password element lt AuthPage type forgotPassword gt path update password element lt AuthPage type updatePassword gt LoginPage gt lt AuthPage type login providers name google label Sign in with Google gt notificationProvider notificationProvider ReadyPage ReadyPage catchAll lt ErrorComponent gt Layout Layout gt export default App Focusing on the top in order to add a resource to our app we have to introduce the resources prop to lt Refine gt The value of resources prop should be an array of resource items with RESTful routes in our app A typical resource object contains properties and values related to the resource name options and intended actions Typical resource object inside resources array name canvases options label Canvases list CanvasList show CanvasShow We can have as many resource items inside our resources array as the number of entities we have in our app refine simplifies CRUD actions and routing related to all items in the resources array It s worth spending a few minutes exploring the possible properties of a resource item from the resources docs here For the above canvases resource the name property denotes the name of the resource Behind the scenes refine auto magically adds RESTful routes for the actions defined on a resource name to the routerProvider object i e for us here along the canvases path We ll ignore the options object for now but list and show properties represent the CRUD actions we want And their values are the components we want to render when we navigate to their respective RESTful routes such as canvases and canvases show a canvas slug Once again refine generates these routes places them into the routerProvider object It then matches them to their corresponding components when these routes are visited We will use a modal form for the create action so we don t need canvases create route Therefore we won t assign create property for canvases resource Adding resources to lt Refine gt For our app we ll configure our resources object with actions for canvases So let s add canvases resource with list and show actions App tsx lt Refine highlight start resources name canvases option label Canvases list CanvasList show CanvasShow highlight end gt We will consider these two actions with their respective components in the coming sections We should have the CanvasList and CanvasShow components premade In a refine app CRUD action related components are typically placed in a directory that has a structure like this src pages resource name In our case we ll house canvases related components in the src pages canvases folder index FilesWe are also using index ts files to export contents from our folders so that the components are easily found by the compiler in the global namespace Adding required filesHere is the finalized version of what we ll be building in this article Before we move on you need to add required page and components to the project if you want build the app by following the article Please add the following components and files into src folder in the project pages components utility types styles After creating files above you need to add some imports to App tsx simply add replace your App tsx with following App tsximport React from react import Refine from pankod refine core import AuthPage notificationProvider ReadyPage ErrorComponent Icons from pankod refine antd import pankod refine antd dist reset css import dataProvider liveProvider from pankod refine supabase import routerProvider from pankod refine react router v import supabaseClient from utility import authProvider from authProvider import Layout from components layout import CanvasFeaturedList CanvasList CanvasShow from pages canvases import styles style css const GithubOutlined Icons function App return lt Refine dataProvider dataProvider supabaseClient liveProvider liveProvider supabaseClient authProvider authProvider routerProvider routerProvider routes path register element lt AuthPage type register gt path forgot password element lt AuthPage type forgotPassword gt path update password element lt AuthPage type updatePassword gt LoginPage gt lt AuthPage type login providers name github icon lt GithubOutlined style fontSize px gt label Sign in with GitHub gt resources name canvases options label Canvases list CanvasList show CanvasShow notificationProvider notificationProvider ReadyPage ReadyPage catchAll lt ErrorComponent gt Layout Layout gt export default App lt Refine gt list ActionThe list action represents a GET request sent to the canvases table in our Supabase db It is done through the dataProvider getList method that pankod refine supabase gave us From the consumer lt CanvasList gt component it can be accessed via the useList hook refine defines the routes for list action to be the canvases path and adds it to the routerProvider object canvases path in turn renders the lt CanvasList gt component as specified in the resources array The contents of our lt CanvasList gt component look like this src pages canvases list tsximport AntdList Skeleton useSimpleList from pankod refine antd import CanvasTile from components canvas import SponsorsBanner from components banners import Canvas from types export const CanvasList React FC gt const listProps queryResult useSimpleList lt Canvas gt resource canvases pagination pageSize initialSorter field created at order desc const isLoading queryResult return lt div className container gt lt div className paper gt isLoading lt div className canvas skeleton list gt Array map index gt lt Skeleton key index paragraph rows gt lt div gt lt AntdList listProps className canvas list split false renderItem canvas gt lt CanvasTile canvas canvas gt gt lt div gt lt SponsorsBanner gt lt div gt There are a few of things to note here the first being the use of Ant Design with refine s pankod refine antd module The second thing is the useSimpleList hook that is being used to access listProps and queryResult items to feed UI elements And third the use of pagination and sorting in the query sent Let s briefly discuss what s going on refine antd Componentsrefine makes all Ant Design components available to us via the pankod refine antd package They can be used with their same name in Ant Design However Ant Design s lt List gt component is renamed as lt AntdList gt which we are using above It takes in the props inside listProps object that useSimpleList hook prepares for us from the fetched canvases array and shows each canvas data inside the lt CanvasTile gt component All the props and presentation logic are being handled inside the Ant Design lt List gt component For detailed info on the lt List gt component please visit this Ant Design reference Refer to complete refine CRUD app with Ant Design tutorial here useSimpleList HookThe useSimpleList is a pankod refine antd hook built on top of the low level useList hook to fetch a resource collection After fetching data according to the the value of the resource property it prepares it according to the listProps of the Ant Design s lt List gt component In our lt CanvasList gt component we are passing the listProps props to lt AntdList gt in order to show a list of canvases Please feel free to go through the useSimpleList documentation here for as much as information as you need It makes life a lot easier while creating a dashboard or list of items SortingIf you are already looking at the useSimpleList argument object s properties notice that we are able to pass options for pagination and initialSorter for the API call and get the response accordingly With this set up and connected to the Internet if we run the dev server with yarn dev and navigate to http localhost we are faced with a login screen Well That s mean Okay this is because we have authProvider prop activated in the boilerplate lt App gt component Additionally the LoginPage prop was also set to refine s special lt AuthPage gt component Because of this we are being presented with the lt AuthPage gt component s login type variant which basically wants us to authenticate before we move forward Also you can inspect the pages auth index tsx component to see how we customized the default Auth Page component However we want our gallery at canvases to be public So we need to bypass authentication for this path And we can do that by tweaking the authProvider checkAuth method Let s look at its current implementation and discussn the whats and hows before we come up with the changes Public Routes in refineIf we revisit the authProvider object we can see that the checkAuth method only allows logged in users into the root route All other attempts are rejected src authProvider tscheckAuth async gt const session supabaseClient auth session const sessionFromURL await supabaseClient auth getSessionFromUrl if session sessionFromURL data user return Promise resolve return Promise reject We ll change this to be the opposite To check for the session from the current url and allow all users to src authProvider tscheckAuth async gt await supabaseClient auth getSessionFromUrl return Promise resolve We ll modify the getUserIdentity method as well because we are using it in the lt Header gt component which houses a button for creating a canvas src authProvider tsgetUserIdentity async gt const user supabaseClient auth user if user return Promise resolve user name user email return Promise reject Now if we refresh our browser at we see it redirected to canvases This is because when the resources object is set refine configures the root route to be the list action of the first resource item in the resources array Since we only have canvases as our resource it leads to canvases At the moment we don t have any canvas created in our app yet so at canvases we don t see the gallery The change in checkAuth brings caveats as removing the return Promise reject disables the LoginPage prop of lt Refine gt so with this change we will get a error when we visit login We ll come back to this in the section related to Authentication But let s now go ahead and implement how to create canvases lt Refine gt create ActionThe create action represents a POST request sent to the canvases table in our Supabase database It is done with the dataProvider create method that pankod refine supabase package gave us We are presenting the canvas form inside a modal contained in a lt CreateCanvas gt component which is placed in the lt Header gt component And the modal is accessed with a Create canvas button we have in the lt Header gt The lt Header gt component looks like this src components layout header index tsximport React from react import useGetIdentity useLogout useMenu useNavigation useRouterContext from pankod refine core import Button Image Space Icons useModalForm from pankod refine antd import CreateCanvas from components canvas import Canvas from types const PlusSquareOutlined LogoutOutlined LoginOutlined Icons export const Header React FC gt const Link useLocation useRouterContext const isError useGetIdentity const mutate mutateLogout useLogout const push useNavigation const selectedKey useMenu const pathname useLocation const modalProps formProps show useModalForm lt Canvas gt resource canvases action create redirect show const isLogin isError const handleRedirect gt if pathname push login push login to encodeURIComponent pathname return lt div className container gt lt div className layout header gt lt Link to gt lt Image width px src pixels logo svg alt Pixels Logo preview false gt lt Link gt lt Space size large gt lt Link to className nav button selectedKey active gt lt span className dot icon gt HOME lt Link gt lt Link to canvases className nav button selectedKey canvases active gt lt span className dot icon gt NEW lt Link gt lt Space gt lt Space gt lt Button icon lt PlusSquareOutlined gt onClick gt if isLogin show else handleRedirect title Create a new canvas gt Create lt Button gt isLogin lt Button type primary danger onClick gt mutateLogout icon lt LogoutOutlined gt title Logout gt lt Button type primary onClick gt handleRedirect icon lt LoginOutlined gt title Login gt Login lt Button gt lt Space gt lt div gt lt CreateCanvas modalProps modalProps formProps formProps gt lt div gt Our create action involves the useModalForm hook which manages UI state error and data fetching for the refine antd lt Modal gt and lt Form gt components Let s zoom in on what exactly it is doing The useModalForm HookIn the lt Header gt component above we are invoking the useModalForm hook with its argument object containing resource action and redirect properties We are getting the modalProps and formProps properties that it prepares for us from the response data There are loads of things happening here So I recommend going through the useModalForm documentation It is also important that we understand how the Ant Design lt Modal gt component accepts the modalProps props from this page and how the lt Form gt works with formProps from here We are using the lt Modal gt and lt Form gt inside the lt CreateCanvas gt component that receives the modalProps and formProps and relays them to these descendents CreateCanvas component code src components canvas create tsximport React useState from react import useGetIdentity from pankod refine core import Form FormProps Input Modal ModalProps Radio from pankod refine antd import getRandomName DEFAULT CANVAS SIZE from utility type CreateCanvasProps modalProps ModalProps formProps FormProps export const CreateCanvas React FC lt CreateCanvasProps gt modalProps formProps gt const data user useGetIdentity const values setValues useState gt const name getRandomName return name name id name replace s g toLowerCase width DEFAULT CANVAS SIZE height DEFAULT CANVAS SIZE return lt Modal modalProps title Create Canvas width centered afterClose gt const name getRandomName setValues name name id name replace s g toLowerCase width DEFAULT CANVAS SIZE height DEFAULT CANVAS SIZE bodyStyle borderRadius px gt lt Form formProps labelCol span wrapperCol span onFinish gt return formProps onFinish amp amp formProps onFinish values user id user id gt lt Form Item label ID gt lt Input value values id disabled gt lt Form Item gt lt Form Item label Name gt lt Input value values name disabled gt lt Form Item gt lt Form Item label Size gt lt Radio Group options onChange target value gt setValues p gt p height value width value value values width optionType button buttonStyle solid gt lt Form Item gt lt Form gt lt Modal gt Notice the use of the formProps onFinish method on lt Form gt s onFinish prop This is the form event which initiates the create action Behind the scenes useModalForm ultimately calls the useCreate data hook which fetches the data with the dataProvider create method For details about how the useCreate hook works please refer to this refine documentation Notice also that we are passing the redirect property to the useModalForm hook which specifies that we redirect to the show action of the resource We ll come to this in the next section related to adding show action in our canvases resource If we now click on the Create button in our navbar we will be again redirected to the login page This is because for the onClick event on the Create canvas button inside the lt Header gt component we have asked the router to authenticate the user if they are not logged in src components layout header index tsx lt Button icon lt PlusSquareOutlined gt onClick gt if isLogin show else handleRedirect title Create a new canvas gt Create lt Button gt And because of the change we made in authProvider checkAuth we get a error Let s just bypass authentication by disabling the authProvider prop on lt Refine gt by commenting it out src App tsx lt Refine authProvider authProvider gt Now if we click on the Create canvas button on the navbar we should be presented with a modal with the form inside So we are able to see the form for canvas create action but can t really create a canvas because we don t have a user id as we have authentication disabled at this point We ll start creating canvases after we have our show page ready and once we have authentication fully implemented and reactivated lt Refine gt show ActionWe noted in the previous section that after a successful create action useModalForm is set to redirect the page to the show action The show action represents a GET request to the canvases table in our Supabase database It is done with the dataProvider getOne method In the lt CanvasShow gt component it can be accessed via the useShow hook The lt CanvasShow gt component looks like this src pages canvases show tsximport useState from react import useCreate useGetIdentity useNavigation useShow from pankod refine core import Button Typography Icons Spin from pankod refine antd import CanvasItem DisplayCanvas from components canvas import ColorSelect from components color select import AvatarPanel from components avatar import colors from utility import Canvas from types const LeftOutlined Icons const Title Typography export const CanvasShow React FC gt const color setColor useState lt typeof colors number gt black const data identity useGetIdentity const queryResult data data canvas useShow lt Canvas gt const mutate useCreate const list push useNavigation const onSubmit x number y number gt if identity return push login if typeof x number amp amp typeof y number amp amp canvas id mutate resource pixels values x y color canvas id canvas id user id identity id successNotification false return lt div className container gt lt div className paper gt lt div className paper header gt lt Button type text onClick gt list canvases style textTransform uppercase gt lt LeftOutlined gt Back lt Button gt lt Title level gt canvas name canvas id lt Title gt lt Button type text style visibility hidden gt lt LeftOutlined gt Back lt Button gt lt div gt canvas lt DisplayCanvas canvas canvas gt pixels gt pixels lt div style display flex justifyContent center gap gt lt div gt lt ColorSelect selected color onChange setColor gt lt div gt lt CanvasItem canvas canvas pixels pixels onPixelClick onSubmit scale canvas width active true gt lt div style width gt lt AvatarPanel pixels pixels gt lt div gt lt div gt lt div className spin wrapper gt lt Spin gt lt div gt lt DisplayCanvas gt lt div className spin wrapper gt lt Spin gt lt div gt lt div gt lt div gt In the code above we have two instances of data hooks in action First with the useShow hook we are getting the created canvas data to display it in the grid src pages canvases show tsxconst queryResult data data canvas useShow lt Canvas gt Additionally we are letting another mutation to create a pixel in our pixels table with the following src pages canvases show tsxconst mutate useCreate const onSubmit x number y number gt if typeof x number amp amp typeof y number amp amp canvas id mutate resource pixels values x y color canvas id canvas id Now that we have our lt CanvasShow gt component ready let s start implementing Supabase authentication for our app Supabase Authentication with RefineLet s re activate authentication by uncommenting authProvider authProvider src App tsx lt Refine authProvider authProvider gt And if we click on the Create canvas button we are redirected to login route that leads to the error Email Authentication with Supabase in RefineFor implementing authentication we look back at the App tsx file refine s Supabase module has produced all the auth page variations we need to register an account login recover password and update password along with the code for routing https requests and authentication providers Namely authentication related routing has been added src App tsx lt Refine routerProvider routerProvider auth routes start routes path register element lt AuthPage type register gt path forgot password element lt AuthPage type forgotPassword gt path update password element lt AuthPage type updatePassword gt auth routes end gt The LoginPage prop was also added src App tsx lt Refine LoginPage gt lt AuthPage type login providers name github label Sign in with GitHub gt gt However we changed the authProvider checkAuth method earlier in order to accommodate our public gallery Because of this change the LoginPage prop gets deactivated So in the following section we are moving the login page to the routes prop Custom LoginIn order to add a custom login route we add a new entry to the routes prop of lt Refine gt You can replace your App tx with the following src App tsximport Refine from pankod refine core import notificationProvider ReadyPage ErrorComponent Icons ConfigProvider from pankod refine antd import dataProvider liveProvider from pankod refine supabase import routerProvider from pankod refine react router v import Layout from components layout import CanvasFeaturedList CanvasList CanvasShow from pages canvases import AuthPage from pages auth import supabaseClient from utility import authProvider from authProvider import pankod refine antd dist reset css import styles style css const GithubOutlined Icons function App return lt ConfigProvider theme token colorPrimary ecfe colorText a colorError fac colorBgLayout fff colorLink ecfe colorLinkActive ecfe colorLinkHover ecfe gt lt Refine dataProvider dataProvider supabaseClient liveProvider liveProvider supabaseClient authProvider authProvider routerProvider routerProvider routes path login element lt AuthPage type login providers name github icon lt GithubOutlined style fontSize px gt label Sign in with GitHub gt path register element lt AuthPage type register gt path forgot password element lt AuthPage type forgotPassword gt path update password element lt AuthPage type updatePassword gt DashboardPage gt lt CanvasFeaturedList gt resources name canvases list CanvasList show CanvasShow notificationProvider notificationProvider ReadyPage ReadyPage catchAll lt ErrorComponent gt Layout Layout gt lt ConfigProvider gt export default App We are also using a customized version of the lt AuthPage gt component now We will not discuss about customizing the lt AuthPage gt component since it is pretty straight forward But you can find the updated lt AuthPage gt component in the src pages auth directory If you haven t already it is definitely worth spending time to go over the lt AuthPage gt customization details here Registering an AccountSince we haven t created any account with the auth users table on our Supabase server we need to navigate to the register route where we are presented with the customized sign up form At this point if we register with our email and a password it gets added to the auth users table in Supabase After registration the user is automatically signed in and the browser redirects to the root route which takes us to the canvases route thanks to refine s sensible routing defaults And now since we are logged in we should be able to create a canvas After successful creation of a canvas we should be redirected to canvases id Feel free to create a few more canvases and draw on them so that the gallery gets populated With the main features functioning now let s focus on adding and activating third party authentication We have a providers prop on lt AuthPage gt We want to add GitHub authentication as well GitHub Authentication with Supabase in RefineWe implemented GitHub authentication with Supabase in our app In order to do so we just need to add the following object to the providers prop in lt AuthPage gt component name github icon lt GithubOutlined style fontSize px gt label Sign in with GitHub In our Supabase backend we have to configure and enable GitHub authentication Feel free to use this Supabase guide And now we should be able to sign in to our app with GitHub as well Implementing a Public Dashboard with RefineNow it s time to focus on the DashboardPage prop We put the lt CanvasFeaturedList gt in this page App tsx lt Refine Dashboard gt lt CanvasFeaturedList gt gt The DashboardPage prop places its component at the route and it precedence over the first item in the resources prop So now if we visit the root route we can see the lt CanvasFeaturedList gt component and not the lt CanvasList gt component There will not be any item in the dashboard page because is featured is set to false for a canvas by default At this stage in order to get a list of featured canvases we have to set is featured true from Supabase dashboard for some of the canvases created I ve done that and the featured canvases are listed in the Home route SummaryIn this post we added canvases resource to our lt Refine gt component We implemented list action on a public gallery and a dashboard page and the show action to display a canvas The create action is implemented from inside a modal accessible on a button click While working through these we inspected into individual data provider methods and hooks for these actions We also saw how refine handles a simple email password based authentication out of the box We then went ahead implemented social login using GitHub authentication provider In the next article we ll move things to the next level by adding live collaboration features using refine s Supabase liveProvider 2023-02-16 08:37:42
海外TECH DEV Community Null safety: Kotlin vs. Java https://dev.to/nfrankel/null-safety-kotlin-vs-java-13pn Null safety Kotlin vs JavaLast week I was at the FOSDEM conference FOSDEM is specific in that it has multiple rooms each dedicated to a different theme and organized by a team I had two talks Practical Introduction to OpenTelemetry Tracing in the Monitoring and Observability devroomWhat I miss in Java the perspective of a Kotlin developer in the Friends of OpenJDK devroomThe second talk is from an earlier post Martin Bonnin did a tweet from a single slide and it created quite a stir even attracting Brian Goetz Martin Bonnin ️ martinbonnin How many different nullability annotation exist in Java AM Feb In this post I d like to expand on the problem of nullability and how it s solved in Kotlin and Java and add my comments to the Twitter thread NullabilityI guess that everybody in software development with more than a couple of years of experience has heard the following quote I call it my billion dollar mistake It was the invention of the null reference in At that time I was designing the first comprehensive type system for references in an object oriented language ALGOL W My goal was to ensure that all use of references should be absolutely safe with checking performed automatically by the compiler But I couldn t resist the temptation to put in a null reference simply because it was so easy to implement This has led to innumerable errors vulnerabilities and system crashes which have probably caused a billion dollars of pain and damage in the last forty years Tony HoareThe basic idea behind null is that one can define an uninitialized variable If one calls a member of such a variable the runtime locates the memory address of the variable and fails to dereference it because there s nothing behind it Null values are found in many programming languages under different names Python has NoneJavaScript has nullSo do Java Scala and KotlinRuby has niletc Some languages do not allow uninitialized values such as Rust Null safety in KotlinAs I mentioned Kotlin does allow null values However they are baked into the type system In Kotlin every type X has two indeed two types X which is non nullable No variable of type X can be null The compiler guarantees it val str String nullThe code above won t compile X which is nullable val str String nullThe code above does compile If Kotlin allows null values why do its proponents tout its null safety The compiler refuses to call members on possible null values i e nullable types val str String getNullableString val int Int str toIntOrNull Doesn t compileThe way to fix the above code is to check whether the variable is null before calling its members val str String getNullableString val int Int if str null null else str toIntOrNull The above approach is pretty boilerplate y so Kotlin offers the null safe operator to achieve the same val str String getNullableString val int Int str toIntOrNull Null safety in JavaNow that we have described how Kotlin manages null values it s time to check how Java does it First there are neither non nullable types nor null safe operators in Java Thus every variable can potentially be null and should be considered so var MyString str getMyString var Integer anInt null if str null anInt str toIntOrNull String has no toIntOrNull method so let s pretend MyString is a wrapper type and delegates to StringA mutable reference is necessaryIf you chain multiple calls it s even worse as every return value can potentially be null To be on the safe side we need to check whether the result of each method call is null The following snippet may throw a NullPointerException var baz getFoo getBar getBaz Here s the fixed but much more verbose version var foo getFoo var bar null var baz null if foo null bar foo getBar if bar null baz bar getBaz For this reason Java introduced the Optional type Optional is a wrapper around a possibly null value Other languages call it Maybe Option etc Java language s designers advise that a method returns Type X if X cannot be nullType Optional lt X gt if X can be nullIf we change the return type of all the above methods to Optional we can rewrite the code in a null safe way and get immutability on top final var baz getFoo flatMap Foo getBar flatMap Bar getBaz orElse null My main argument regarding this approach is that the Optional itself could be null The language doesn t guarantee that it s not Also it s not advised to use Optional for method input parameters To cope with this annotation based libraries have popped up ProjectPackageNon null annotationNullable annotationJSR javax annotation Nonnull NullableSpringorg springframework lang NonNull NullableJetBrainsorg jetbrains annotations NotNull NullableFindbugsedu umd cs findbugs annotations NonNull NullableEclipseorg eclipse jdt annotation NonNull NullableChecker frameworkorg checkerframework checker nullness qual NonNull NullableJSpecifyorg jspecify NonNull NullableLombokorg checkerframework checker nullness qual NonNull However different libraries work in different ways Spring produces WARNING messages at compile timeFindBugs requires a dedicated executionLombok generates code that adds a null check but throws a NullPointerException if it s null anywayetc Thanks to Sébastien Deleuze for mentioning JSpecify which I didn t know previously It s an industry wide effort to deal with the current mess Of course the famous XKCD comic immediately comes to mind I still hope it will work out ConclusionJava was incepted when null safety was not a big concern Hence NullPointerException occurrences are common The only safe solution is to wrap every method call in a null check It works but it s boilerplate y and makes the code harder to read Multiple alternatives are available but they have issues they aren t bulletproof compete with each other and work very differently Developers praise Kotlin for its null safety it s the result of its null handling mechanism baked into the language design Java will never be able to compete with Kotlin in this regard as Java language architects value backward compatibility over code safety It s their decision and it s probably a good one when one remembers the pain of migration from Python to Python However as a developer it makes Kotlin a much more attractive option than Java to me To go further Are there languages without null Kotlin nullable types and non null typesJSpecifyOriginally published at A Java Geek on February th 2023-02-16 08:02:00
医療系 医療介護 CBnews コロナ入院患者数5週連続減少、重症患者数は半減-東京都が感染状況・医療提供体制の分析公表 https://www.cbnews.jp/news/entry/20230216173240 通常医療 2023-02-16 17:45:00
医療系 医療介護 CBnews 多発性骨髄腫薬ダラキューロで費用削減効果、中医協-尿路上皮癌薬バドセブは費用増で薬価引き下げ https://www.cbnews.jp/news/entry/20230216170613 中央社会保険医療協議会 2023-02-16 17:20:00
医療系 医療介護 CBnews ロタウイルスワクチン接種でアナフィラキシー反応-医薬品・医療機器等安全性情報に副反応の症例記載 https://www.cbnews.jp/news/entry/20230216163447 医療機器 2023-02-16 17:05:00
海外ニュース Japan Times latest articles Lewis Hamilton vows to continue speaking out about social issues https://www.japantimes.co.jp/sports/2023/02/16/more-sports/auto-racing/lewis-hamilton-vows-continue-speaking-social-issues/ Lewis Hamilton vows to continue speaking out about social issuesHamilton has used his platform to highlight racial injustice promote diversity and address a range of issues from the environment to human rights 2023-02-16 17:30:26
ニュース BBC News - Home Profits triple at British Gas owner after energy prices soar https://www.bbc.co.uk/news/business-64652142?at_medium=RSS&at_campaign=KARANGA ukraine 2023-02-16 08:26:27
ニュース BBC News - Home New Zealand v England: Late wickets vindicate tourists' declaration on day one https://www.bbc.co.uk/sport/cricket/64658993?at_medium=RSS&at_campaign=KARANGA New Zealand v England Late wickets vindicate tourists x declaration on day oneEngland s decision to declare on is vindicated by three late wickets on the first day of the day night first Test against New Zealand in Mount Maunganui 2023-02-16 08:44:12
ニュース Newsweek 本の要約サービス「フライヤー」CEO・大賀康史が選ぶ2022年のベスト本3冊 https://www.newsweekjapan.jp/stories/business/2023/02/post-100861.php 『人を選ぶ技術』著者小野壮彦出版社フォレスト出版要約を読む※画像をクリックするとアマゾンに飛びます年は人的資本経営、リスキリングなどの人材に関わるトピックが話題となった一年ではなかったでしょうか。 2023-02-16 17:33:00
IT 週刊アスキー 子育てを応援。小田急電鉄の下北沢駅など7駅にて完全個室のベビーケアルーム「mamaro(ママロ)」3月1日より展開開始 https://weekly.ascii.jp/elem/000/004/125/4125157/ mamaro 2023-02-16 17:50:00
IT 週刊アスキー 『トワツガイ』本日サービス開始!ゲーム外のさまざまな企画も紹介 https://weekly.ascii.jp/elem/000/004/125/4125154/ 開始 2023-02-16 17:20:00
IT 週刊アスキー 『シアトリズム ファイナルバーライン』が本日発売!「SaGaシリーズパック」も配信 https://weekly.ascii.jp/elem/000/004/125/4125156/ nintendo 2023-02-16 17:15: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件)