IT |
気になる、記になる… |
Amazon、Kindleストアで「講談社 まとめ買いキャンペーン」のセールを開催中 − 「ザ・ファブル」や「宇宙兄弟」の全巻セットが20%オフに |
https://taisy0.com/2021/06/14/141837.html
|
公開予定 |
2021-06-14 14:01:43 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
残プロ 第-13回 ~pythonで定期的に画面キャプチャ~ |
https://qiita.com/R1nY1x1/items/37df847ff4bd2c55e57e
|
|
2021-06-14 23:57:57 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
EJSで作業効率化 |
https://qiita.com/Coco_syu/items/a1ed7aa7c97fc00ce8d8
|
今まではiscurrentやisactiveクラスの付け外しで見た目を変えていくことで実装していたが、EJSを使えば、共通のナビゲーションモジュールとして外部化し、if文を使ってモジュール内部で分岐を行うことで、「ファイルだけ編集すれば、読み込むすべてのファイルで編集が適用され、場合分けもできる」という非常に効率的な状態にすることができる。 |
2021-06-14 23:57:42 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
Nodebrew を使って Node.js をインストールしてみた |
https://qiita.com/tomokoqiitta/items/985284e5a4621d23347d
|
Nodebrewを使ってNodejsをインストールしてみたはじめに年月開講の医療者向けプログラミングスクール「ものづくり医療センター」に期生として参加させていただくことになった。 |
2021-06-14 23:28:22 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
ボタンを押したときにくるくるローディングさせるやつ |
https://qiita.com/takiguchi-yu/items/aa32779c99acb022aec5
|
chiyutakiguchiyuoncodepen |
2021-06-14 23:23:56 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
OpenWeatherMap のCityID検索用サービスを作ってみた |
https://qiita.com/tkyko13/items/e52627dfcff581bed360
|
OpenWeatherMapのCityID検索用サービスを作ってみた無料で多機能な天気系APIの一つOpenWeatherMap使い方として、以下のjsonから対応した都市の名前を探して、一致した名前をリクエストするもの例jpampAPPIDAPIKEY注意APIKEY取得しなければいけません無料自宅付近の府中見つけたけど確か広島にも府中ってあったよな…先程のjsonデータをダウンロードしてきて、府中に住んでいるので「fuchu」と検索したらありました。 |
2021-06-14 23:16:53 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
今見ているサイトのGoogleAnalyticsトラッキングIDを表示するブックマークレット |
https://qiita.com/YUTA_NARIKAWA_MEM/items/687c943d2751ece13c83
|
今見ているサイトのGoogleAnalyticsトラッキングIDを表示するブックマークレット閲覧しているサイトのGoogleAnalyticsユニバーサルアナリティクスのトラッキングIDUA〇〇〇〇をスピーディに表示します。 |
2021-06-14 23:06:14 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
import talibでエラーが出ないようにする方法を教えてください。 |
https://teratail.com/questions/343997?rss=all
|
importtalibでエラーが出ないようにする方法を教えてください。 |
2021-06-14 23:51:39 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
バッチファイルにすると起動しません。 |
https://teratail.com/questions/343996?rss=all
|
連番を動画としてエンコードできるように行っているのですが、バッチファイルにした時のみの部分にパッチファイルのパスがなぜか代入されてしまいます。 |
2021-06-14 23:45:02 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
JavaScript appendChildした要素を動的に逆順にするには |
https://teratail.com/questions/343995?rss=all
|
|
2021-06-14 23:32:34 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
c言語 バブルソート 文字列 |
https://teratail.com/questions/343994?rss=all
|
c言語バブルソート文字列バブルソートで、数字の昇順に合わせて、それに対応する文字列例えばdataに対応する文字列はnameのquotomegaquotも一緒に並び替えたいのですが、うまくいきませんでした。 |
2021-06-14 23:29:42 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
VScodeを使ってpython,plotlyでチャートを表示させようとしましたが、表示されませんでした。 |
https://teratail.com/questions/343993?rss=all
|
VScodeを使ってpythonplotlyでチャートを表示させようとしましたが、表示されませんでした。 |
2021-06-14 23:28:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
openFileDialogコントロールの「開く」ダイアログ画面で「開く」ボタンの名称を変更したい。 |
https://teratail.com/questions/343992?rss=all
|
openFileDialogコントロールの「開く」ダイアログ画面で「開く」ボタンの名称を変更したい。 |
2021-06-14 23:18:01 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
スプレッドシートで縦に並ぶ連続データから条件に当てはまる組み合わせの個数等を計算したい |
https://teratail.com/questions/343991?rss=all
|
スプレッドシートで縦に並ぶ連続データから条件に当てはまる組み合わせの個数等を計算したい前提・実現したいことGoogleスプレッドシートを利用しています。 |
2021-06-14 23:08:31 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
c言語 木構造 辞書的検索 |
https://teratail.com/questions/343990?rss=all
|
c言語木構造辞書的検索木構造での辞書的検索のやり方c言語でnbspquot木構造の中に入力した文字列が存在するかを確認するプログラムquotnbspを作りたいのですが、検索する関数内の条件をうまく書くことができないので、どのような条件と書き方で辞書的な検索ができるのかを教えて欲しいです。 |
2021-06-14 23:02:56 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Herokuデプロイ時にSprockets::DoubleLinkErrorが出た時(メモ) |
https://qiita.com/tech_kento/items/c3efd4fb91c7bea85e01
|
Herokuデプロイ時にSprocketsDoubleLinkErrorが出た時メモHerokuデプロイ時のエラーコードSprocketsDoubleLinkErrorSprocketsDoubleLinkErrorMultiplefileswiththesameoutputpathcannotbelinkedapplicationcssIntmpbuilddecfappassetsconfigmanifestjsthesefileswerelinkedtmpbuilddecfappassetsstylesheetsapplicationcsstmpbuilddecfappassetsstylesheetsapplicationscssエラーコード詳細一行目のエラーコードを読み解くMultiplefileswiththesameoutputpathcannotbelinkedapplicationcss以下、直訳。 |
2021-06-14 23:21:05 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
KryptonでAWSアカウントをセキュアに! |
https://qiita.com/YSFT_KOBE/items/ed79fb2f317ebfd7dad3
|
UFによる認証実施IDPASSWORDでログインすると、MFAを使用してサインインの画面が出たあとに、スマホに通知が出てくるので、「APPROVE」を選択します。 |
2021-06-14 23:36:07 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
AWS実務ほぼなしでAWS資格のネットワーク専門知識に合格した勉強法 |
https://qiita.com/siberiannhasuki_iijima/items/92e370eb3c76f1d09091
|
・気持ちに余裕ができるため、テストセンターは早めに着いておいたほうがいい・受付のあと開始まで時間があったが、センター内で復習はできず、すぐに試験となる・序盤で分くらい迷う問題があったので、解答に迷う問題は仮回答してフラグを立て見直したほうがいい・見直しは最後までやり尽くす問題を受けての所感は、・実施した勉強から割くらい・見たことないが実施した勉強の知識から回答できたのが割くらい・見たことなく、回答もなんとなくしか分からない問題が割という具合で、問くらいはフラグが付きました。 |
2021-06-14 23:07:35 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
AWS CLIの振り返り ~SNS編~ |
https://qiita.com/kuraboshi/items/bf942d5340ca610b9eaa
|
AWSCLIの振り返りSNS編本記事の目的JAWSUGCLIオンラインハンズオンの復習として、ハンズオンで使用したコマンドを箇条書きでまとめる。 |
2021-06-14 23:02:36 |
GCP |
gcpタグが付けられた新着投稿 - Qiita |
FirebaseHostingにchatアプリをデプロイしてみた |
https://qiita.com/yoshii0110/items/e247db8f03a04a2298d8
|
ローカル環境の設定FirebaseCLIを使用し、FirebaseHostingにてWebアプリをFirebaseプロジェクトにデプロイすることができます。 |
2021-06-14 23:48:05 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
Git操作:デフォルトブランチ名の変更 |
https://qiita.com/NeK/items/863ff25a46c6eefeb623
|
|
2021-06-14 23:00:47 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
Herokuデプロイ時にSprockets::DoubleLinkErrorが出た時(メモ) |
https://qiita.com/tech_kento/items/c3efd4fb91c7bea85e01
|
Herokuデプロイ時にSprocketsDoubleLinkErrorが出た時メモHerokuデプロイ時のエラーコードSprocketsDoubleLinkErrorSprocketsDoubleLinkErrorMultiplefileswiththesameoutputpathcannotbelinkedapplicationcssIntmpbuilddecfappassetsconfigmanifestjsthesefileswerelinkedtmpbuilddecfappassetsstylesheetsapplicationcsstmpbuilddecfappassetsstylesheetsapplicationscssエラーコード詳細一行目のエラーコードを読み解くMultiplefileswiththesameoutputpathcannotbelinkedapplicationcss以下、直訳。 |
2021-06-14 23:21:05 |
技術ブログ |
Developers.IO |
[Auth0] 管理ダッシュボードからユーザー作成とMetadata設定を行う |
https://dev.classmethod.jp/articles/create-a-user-and-configure-metadata-from-the-auth0-management-dashboard/
|
metadata |
2021-06-14 14:53:57 |
海外TECH |
Ars Technica |
Metals from space descend on Boulder, Colorado, at dusk and dawn |
https://arstechnica.com/?p=1772509
|
earth |
2021-06-14 14:35:14 |
海外TECH |
Ars Technica |
The CEO and CFO of Lordstown Motors both just resigned |
https://arstechnica.com/?p=1773132
|
concern |
2021-06-14 14:09:56 |
海外TECH |
DEV Community |
What has the Marko Team Been Doing all These Years? |
https://dev.to/ryansolid/what-has-the-marko-team-been-doing-all-these-years-1cf6
|
What has the Marko Team Been Doing all These Years As some of you know I joined the Marko team at eBay a year ago And for many the immediate question was What is Marko Well it s a JavaScript framework like React or Vue built specifically to handle the high performance needs of eBay s platform Performance through server rendering has been critical since day one as eBay is an eCommerce platform and lost milliseconds means lost revenue And there are many platforms with the same requirements but eBay made a pretty bold move in the when they decided to move to fullstack Node for such a platform The first thing they realized were the existing tools weren t going to solve the problem So Marko was created with exactly this in mind But that was years ago and we are seeing other frameworks like React and Astro starting to adopt some of techniques Marko uses So what has Marko been working on Unique OriginsMarko was really built with only main things in mind It needed to have progressive server rendering We need to have the page on the client as soon as possible without waiting for Async but we need to support SEO And we needed to ship the least possible JavaScript to the browser to support all sorts of devices around the world The way to do that is through Partial Hydration Or only sending the JavaScript to the browser for the small parts of the page that were actually interactive And Marko did both of those in The real secret of these two features is that they work together amazingly well If you are streaming your page as it loads but that content is mostly static and can be eliminated from the client JavaScript you send to the browser you can get fully dynamic page loads with skeleton placeholders with kb of JavaScript bundle sizes That is immediate rendering with content progressively loading in without pulling in the big framework bundles Nothing else does that today But a few libraries are looking at doing parts of it Maybe the best way to picture this for those up to date on the latest tech is picture if you wrote an app with HTML based template language and used a compiler like Svelte to automatically generate Astro like Islands out of only the code that needs to run in the browser and it s all served to you using something like the upcoming React s Suspense for SSR Yep Sure things were a bit more manual than they are today but the core pieces were there This is a great start to a story but then the difficulty sets in Growing PainsHow do you possibly achieve such futuristic development in Well you pretty much need to write your own Parser Compiler and Bundler It wasn t enough to handle the templates but in order to package things differently for the server you need a bundler So the team created Lasso The idea with Lasso was to compile and serve templates on demand instead of upfront This way dev server startup times could be fast and incremental rebuilds were possible This was important as Marko being one of the earliest library with truly isomorphic development where the same templates worked on server and browser needed to coordinate multiple builds on code changes Honestly it wasn t until Snowpack or Vite that there was a true successor So supporting the growth and tooling around Marko was definitely the focus for the next couple years Partial Hydration got smarter and architecture was streamlined The next groundbreaking release was Marko in where Marko starting to be conscious of browser performance opted into using a VDOM to make improvements However the world had changed in those years Things like React and Webpack had sprung up and most importantly Babel The trend to transpile JavaScript to support modern features before the browsers did Marko was maintaining its full end to end tool chain and was quickly being left in the dust The migration to Marko was also a big effort at eBay as well Internally Marko had its roots as early as and you can imagine even with automated migration scripts there were challenges To put it in perspective for React devs that time span bridges the gap before React existed in Open Source through the createClass days to ES classes and almost to Hooks The Marko team now only people simultaneous supported migrating the eBay platform written mostly on Marko and upgrading the tooling around Marko to be more modern This included the move to Babel replacing Lasso with other bundlers that didn t quite fill the gap support for Testing Library Jest and Storybook The majority of this work happened over and would become Marko FLUURTThe project codenamed FLUURT was an idea that had been floating around really since the release of Marko but there had been no time to pursue it FLUURT is an acronym that Michael Rawlings had come up with that stood for Fast Lean Unified Update amp Render Target The concept is that with sufficient knowledge from compiler analysis it would be possible to produce the optimal code for any target platform Whether that be server browser mobile or even a different JS Framework This is really part effort There is the means and language for analysis and then there is the compilation and runtime to support it Both are immensely difficult challenges The first carries with it all the stigma and DX concerns with understanding how libraries function I ve written about it in Marko Designing a UI Language Some people will not be happy with it but Marko s new Tags API is like a marriage between something like React s Hooks and Svelte s syntax It has all the compiled magic without losing any of the composability Composability is king But so is clear analyzable syntax Blending both is key incidentally to achieving the granularity that we want for code elimination in the browser for Partial Hydration We really needed to go component less not only as a technology but as a language Luckily this aligns with Marko s earliest goal of being a superset of HTML Writing and maintaining code should be as easy as working with HTML templates The second part has been quite the undertaking Marko has already conquered Server rendering Although Marko might have the most efficient Partial Hydration of all JavaScript frameworks today having worked with it at eBay scale for years we know we can do a lot better Generating the suitable client side approach has been a bit of trial and error There are many considerations and details From the ability remove even more static code from the browser to handling of Async consistency and transitions that needed to be ironed out ExperimentationThe team had developed out their first approach before I joined the team It was a top down reconciler similar to a single pass VDOM like you might find in libraries like uhtml or Lit However it didn t let us leverage Hydration as effectively as we would have liked Granularity was going to be the key here especially with the goal of being able to truly only send the necessary JavaScript to the browser The second approach was a runtime reactive approach with precompiled dependencies This reduced the overhead of subscriptions and got performance in Inferno like range in the browser Static dependencies while saving us from having to run computations to determine dependencies like other runtime reactive libraries MobX Vue Solid required the dependencies to be reactive variables themselves This led to over wrapping of expressions and used up more memory It also still put considerable weight on template boundaries We spent most of the fall on the nd attempt before shifting our focus on releasing Marko and related tooling like Vite However this effort wasn t without value We had used it to develop key new features for the Marko compiler First we added an analysis pass that gather s metadata about all your Marko files so that as the compiler transforms the code we can make informed decisions based on the contents of child templates that are imported Secondly we pulled the core parts of the bundler into Marko s compiler so that we have a generic solution to handling code elimination for automatic Partial Hydration While this lets it be bundler agnostic more importantly it gives us the ability to do wider sweeping changes on the final output The SolutionComing back refreshed Michael realized we could compile away the reactivity without the limitations of local compilation We had already built the pieces we needed and the answer ironically is the simplest one we had to date What if the compiler could split a template into multiple exports that were tree shakable around the different inputs props they accepted A parent could decide based on the statefulness of its own data it was passing which exports it needs to import And then through the use of shared scope and inlined calls of those imported methods you could effectively compile away all reactivity but keep a granular update model This doesn t have the problems of the compiled reactivity as you aren t making signals or computations anymore but passing the data as is with simple dirty checks If that sounds familiar it should It s basically how Svelte works on a localized scope except Marko s version transcends files What s next Well we still aren t done yet We have working prototypes and preliminary benchmarks We feel we ve finally found the approach suitable for Marko This is an incredible step forward for compiled JavaScript framework design But there is still more work to do So we ve decided to take a different tact We will be releasing Marko s Tag API in Marko ahead of the release of the new compiler and runtime We can leverage Marko s cross template analysis to give the minimum feature set so that you can get started with the new features and syntax Together with Marko s already powerful Partial Hydration and Streaming Server rendering we can deliver on the developer experience This will also give a good opportunity for feedback We ve been working tirelessly long behind closed doors and we need to do better at making our efforts visible We now are tracking our projects more visibly on Github and intend to give more regular updates We will follow that in the fall with the beta release of the next version of Marko Sometimes good things take a long time But it will be well worth the wait |
2021-06-14 14:45:26 |
海外TECH |
DEV Community |
Video Streaming: How We Got Here and Why It Works So Well |
https://dev.to/codesphere/video-streaming-how-we-got-here-and-why-it-works-so-well-2kg6
|
Video Streaming How We Got Here and Why It Works So WellWhether we re just catching a sports game on our computer video chatting with friends or just watching our favorite streamer play games on Twitch Video streaming has become a huge part of our lives It s nevertheless awe inspiring to take a second to consider how big of a technological marvel it is that this is even possible If you told the most advanced computer scientists just a few decades ago that we had people streaming high definition video and audio from personal computers and phones across the world they d be dumbfounded It s therefore worth taking a closer look at how streaming is not only possible but has become such a consumer friendly industry Not to mention a lucrative one So What Exactly is Streaming All media consumption can be categorized as either streaming Radio Cable TV Twitch or non streaming Video Tapes CDs While non streaming media delivery involves having the entire contents of the file downloaded streaming is the act of delivering data continually as it is being consumed without requiring the recipient to store the data in its entirety While we ve been streaming radio and cable television since the first half of the th century streaming video over the internet presented its own challenges Bandwidth was simply too weak and file sizes were too large to be able to efficiently stream video in the s when the internet was in its infancy How Efficient Video Streaming Became PossibleA crucial point in the development of effective media streaming was the discovery of the Discrete Cosine Transform DCT which is a method of encoding data points in terms of Cosine functions for the sake of data compression While it was conceived by Nasir Ahmed in it would later be used to create the H video compression standard in H was a groundbreaking standard whose use of DCT would become an industry staple until this day H was the first compression standard that made streaming video practical The application of DCT to video compression combined with increased investment in internet infrastructure would allow streaming to develop rapidly over the next two decades Some notable milestones include Modified Discrete Cosine Transform is introduced as a more effective compression method for large datasets is used in the creation of highly efficient audio formats such as MP Mbone is created as a virtual network for streaming data over the internet A band of software engineers called Severe Tire Damage becomes the first group to perform live on the internet over MBone RealNetworks live streams a Yankees vs Mariners baseball game over the internet becoming the first sports game to be broadcasted this way President Bill Clinton holds the first ever presidential webcast streaming video and fielding questions over the internet The video streaming website YouTube is created Some Helpful TermsAs we get into the weeds of how exactly modern video streaming works it s helpful to define some key terms that you might see in your researchBitrate The speed at which data is streamed Commonly measured in Megabits per SecondAdaptive Bitrate Streaming In order to stream video without buffering there must be a constant bitrate In order to achieve this constant bitrate in the face of an insufficient connection Adaptive Bitrate Streaming automatically adjusts the video quality in order to reduce file sizes and maintain the necessary bitrate Transcoding Converting from one compression codec to anotherTransmuxing AKA transcode multiplexing Changing the protocol in which the video is storedTransrating Changing the bitrateTransizing Changing the resolution of the streamed videoContent Delivery Network CDN Networks of servers across a geographic region that can be used to send data across the world efficiently The Streaming ProcessLet s now take a look at the journey streamed video takes to get from its publisher to its recipient First the video and audio are recorded by the publisher If this is not a live stream then this data will be stored on a server ready to be delivered The data is then broken down into small discrete parts called packetsThese packets are compressed most commonly in the H standard Which uses DCT and packed into a protocol that complies with the receiving computer Depending on the device that is requesting the streamed data servers will transcode transmux translate and transize the data so that it works on the user s specific deviceThe compressed and correctly formatted data packets are then shipped over a CDN to the recipient s computerIt is a modern marvel that these steps are able to occur continuously for millions of computers not to mention the incredible quality of the video that is being streamed Thanks for reading What modern technology do you think is amazing that we too often take for granted Let us know down in the comments |
2021-06-14 14:43:25 |
海外TECH |
DEV Community |
`at` coming soon to ECMAScript |
https://dev.to/laurieontech/at-coming-soon-to-ecmascript-1k91
|
at coming soon to ECMAScriptIf you re a JavaScript developer you ve likely used arrays quite a bit They re an essential data structure within the language In fact they re so essential that the array prototype has seen rapid expansion in the past few years with things like flat and filter added And we re not done yet AccessorIn order to access an element in an array you need to know its index Indeces in JavaScript are zero based so the first element is at index const arr a b c d arr this is a arr this is c As you can see in the example above you can access the first element or the third element What about the last element In other languages you might be able to do something like this const arr a b c d arr This is NOT d But not in JavaScript Why not Well as it turns out is already a valid key Arrays are really objects with indeces as keys So arr is looking at the arr object and the value of the key which is undefined The last elementThen how do we access the last element without knowing its index There are ways to do it but its certainly more verbose You can use the length lookup arr arr length this is d Or you have the slice option arr slice this is d Introducing atThat s why the at function is under consideration Instead of those options you d be able to write this instead arr at this is d The great thing about at is that it can replace square brackets all together arr at this is still a And what about an invalid index arr at this is undefinedSeems pretty all encompassing An aside on historyAs it turns out this was attempted before using item However it wasn t web compatible as it clashed with major libraries So at is the current proposal Would you use it Hopefully this will move forward to Stage soon and be officially adopted I can see this being nice syntactic sugar for accessing array elements |
2021-06-14 14:41:59 |
海外TECH |
DEV Community |
How to show different email notifications for different types of users in a TalkJS chat |
https://dev.to/talkjs/how-to-show-different-email-notifications-for-different-types-of-users-in-a-talkjs-chat-2eic
|
How to show different email notifications for different types of users in a TalkJS chatRoles allow you to change the default behavior of TalkJS for different users You can assign roles to a certain group of your users and have full control over which user gets which role Email notifications can then be customized for different roles In this post we will look at how we can set this up TalkJS RolesTalkJS allows different groups of users to have different settings by assigning them a specific role You have full control over which user gets which role For example you may want one group of users to receive email notifications if they have a new message or give another group of users the ability to share files You can do all of this using roles A role allows you to define the following settings for a group of users Allow disallow file or location sharing Create custom email notification templates Configure SMS settings Configure text contact information suppression Configure how links in chat messages will be opened Customize the standard TalkJS user interface using themesYou can create roles from the TalkJS dashboard Let s create two roles with each receiving a different type of email notification Creating a role in TalkJSCreating a role in TalkJS is simple and can be accomplished using the dashboard Add a role in the dashboardTo add a role click on Roles at the top left corner of your dashboard Next click on the Create new role button and put “buyer as the name of the role You can decide if the role will copy data from previous roles or use the default role setting After this you can manage the settings for the role by using the checkboxes next to each setting Assign a role to a userYou assign a role to a user when you create the user For example if the name of the role you created on the dashboard is buyer you can assign this role to the user Alice in your code like this const me new Talk User id name Alice email alice example com photoUrl welcomeMessage Hey there How are you role buyer lt that s the one Make sure the role matches the role name you chose in the dashboard in this case “buyer For the purpose of this example you may want to set the email to an email address you have access to This will allow you to access the email that gets sent Repeat this process except this time create a new role called “seller Create another user and set the role to be “seller At this stage you should have two roles “buyer and “seller and a single user set up with each role How Email notifications are SentIf a user has a role set and has at least one email address they will automatically start receiving email notifications when they are offline Users can have more than one email address and TalkJS will notify all email addresses on record Email notifications are not sent with each message but rather grouped and sent after a period of inactivity to avoid spamming the user s inbox The TalkJS notification system has been carefully designed to send notifications as quickly as possible while ensuring your users do not feel like they re being spammed We use a number of heuristics to get this balance right There are a few conditions that must be met in order to send notifications The user is offline The user is online but has a different conversation selected in the UI The user is online has the current conversation selected in the UI but the browser tab window does not have focus In other words a notification is not sent out when the user has the current conversation selected in the UI and the tab containing TalkJS is focused To keep the email count low subsequent messages are grouped together After a user sends a message TalkJS tracks whether they continue typing A notification is sent when the user has stopped typing for several seconds This notification will contain all of the messages they sent since they first started typing This also holds for group conversations if two users have a quick real time interaction then the notification sent to the other participants will include all messages sent since the first user started typing until the last user stopped typing TalkJS is designed to be a slow chat solution which supports reply via email functionality When a user replies to a notification email their reply will show up in the conversation Managing your email notification settings through the dashboardTo modify the email notification that TalkJS sends first head to the TalkJS Dashboard and then click on Roles in the top left corner inside of the role editor you ll see a section for Email settings The first option you ll see is the Enable Email notifications checkbox When enabled you have the option to change the subject theme and template for your emailThe next option you ll see is the Enable replying to email notifications via email checkbox This allows recipients of email notifications to reply directly to the email that they receive and have the response sent back to the chat You can also decide whether users can send attachments with their replies However no images are allowed to be sent no matter what This is due to being unable to determine the difference between purposefully attached images and those automatically include in the footer such as company logos Use these role settings to send different emails to users depending on whether they are buyers or sellers Complete control over the emails your users receiveThe concept of roles allows you to easily set up different email templates for different types of users We have covered how to create roles how to add a role to a user and finally how to configure the notifications that are sent for a role This provides you with a highly configurable system that can be tailored to your specific needs It also ensures your users are getting relevant notifications that are genuinely helpful and address their unique situations |
2021-06-14 14:21:23 |
海外TECH |
DEV Community |
Build a Splash Page with Next.js using Airtable as a CMS. |
https://dev.to/gsdev/build-a-splash-page-with-next-js-using-airtable-as-a-cms-1o7l
|
Build a Splash Page with Next js using Airtable as a CMS IntroductionLet s build a fully optimized landing page using Airtable and Next js Over the course of this part series you ll work your way up to building a highly scalable landing page with an easy to use custom Airtable CMS In this first post we ll begin with a general overview of Airtable and Next js and why the combination makes an ideal solution for several real world applications You ll also learn how to configure an Airtable base and integrate it with Next js using static site generation SSG In the rest of the series you ll see how you can simplify the solution and scale using Sync Inc Which provides a synchronized cloud based Postgres instance so you can run raw SQL queries against your Airtable data What We re BuildingIn this first post we ll build a simple yet versatile Splash page Splash pages used to be more common in the past but we still see remnants of them in modern applications Splash pages generally are full screen pages that are typically used for a single purpose the most common example would be a page The BriefIn our case we re building a splash page for an up and coming Saas startup that provides uptime monitoring services Our goal is to create an attractive call to action splash page to act as a placeholder while the full site and app are being built This will help ensure the company can capture any early interest in their product and creates a list of followers who are enthusiastic about their upcoming launch By the end you ll have a working fully customizable splash page built using Airtable as a CMS with markdown support statically generated by Next jswith built in SEO support and image optimization Later in the series you ll learn how you can simplify the integration with Sync Inc scale using a fully provisioned cloud Postgres database leverage the power and simplicity of raw SQL queries Visit Splash Page Demo What is Airtable Airtable is an online platform for managing and sharing relational data in an easy to use collaborative workspace On the surface Airtable looks like a fun spreadsheet but functions like a robust relational database and provides various tools integrations and automations that make it a very effective solution for most use cases Why Airtable Generous Free TierPowerful Automations What is Next js Next js is a highly versatile production grade React framework It provides thoughtful optimizations that just work such as a built in CDN server less functions and link prefetching To take it one step further Next js allows the developer to choose between static and server rendering on a per page page basis Why Next js Super fast performant websites and applicationsOptimized for production from the startDeveloper s choice Static or Server RenderingTypescript and CSS Support PrerequisitesBasic understanding of Javascript ES and React General understanding of relational databases SQL statements and joins System RequirementsNode js or laterEither macOS Windows including WSL or Linux ResourcesAirtable Base This is the Airtable database you ll be working from Starter Repo You can use this repo to clone our starter and follow along Finished Branch Use this repo to compare your work if you run into any issues CodeSandbox Starter You can also follow along using this CodeSandbox starter project Project Demo This is a working demo of the Splash page project from this post Airtable SetupFirst let s get an Airtable base set up Create an airtable account or sign into your airtable account Then click here to Clone the Airtable base you ll be using for this project Airtable CredentialsOnce you ve cloned your base you ll need both your Airtable API key and base id to configure your application NOTE The API key should be treated as a secret and should be kept confidential The base id is semi private but for this project we ll be treating it as a secret as well Generate API keyLet s start by generating your Airtable API key Click on your user icon in the top right hand corner From the drop down menu select the Account option Under Account Overview click the button labeled Generate API key ️Keep this API key secure you ll need it when you configure your Next js application Locate Base IdYou can find your base id from Airtable s live documentation From your base click the Help button on the top right of your screen From the sidebar menu click the link labeled API documentation You ll find your base id listed right under the second paragraph in green ️Keep your base id secure but available you ll need it to configure your Airtable base with your Next js application Once you have your Airtable credentials let s move on to setting up your Next js application Structuring Airtable as a CMSIf this is your first time using Airtable then this section will get you up to speed on some of the terminology and concepts you ll need to proceed The base you cloned is designed to be very flexible so you can always add fields to customize it once you re semi familiar with how it functions Inside your base you will find several tables listed at the top of the screen pages sections blocks media and seo These tables help us arrange our data logically in a way that resembles a spreadsheet but functions like a relational database As shown above each table in a base consists of a collection of rows and each row represents an individual record Records are a collection of fields that hold specific data about the object they represent More about Airtable structureAirtable provides you with various field types that can be used to store all kinds of values For this project we ll only be using a few of the more common field types Single line text used to store small strings of text Number can be configured to hold integers or floating points Long text used for longer text content i e paragraphs Single select select a single option from a predefined list Multiple select select multiple options from a predefined list Attachment used to store files Linked Records used to link a record from one table with another NOTE Even though all of this may seem like a lot we re actually just scratching the surface here with Airtable Luckily they have some incredible documentation both for the platform and for the API And if you really want to dive deep I came across this article that covers just about everything you can do with Airtable as a developer TablesWe use Airtable s field types in our base to help organize our data based on the type of values we want to accept for any given field Let s take a deeper look at each field and the type of data it holds pagesfieldfield typedescriptiontitlesingle line textrepresents the title for the current page and can be used to populate nav menus as needed pathsingle line textused to populate the href value when linking to a page ordernumberused to control the order in which each page should be displayed also useful for nav menus sectionIdlinked recordused to link to related sections for each page seoIdlinked recordused to link to SEO metadata for each page sectionsfieldfield typedescriptiontitlesingle line textrepresents the title for the section only used for reference purposes ordernumberused to control the order of each section on a per page basis typesingle selectused to control which component the application will use to render each section filtermultiple selectused as a boolean modifier that is useful for conditionally rendering components or layouts blockIdlinked recordused to link to related blocks for each section pageIdlinked recordused to link to the page that will render this section blocksfieldfield typedescriptiontitlesingle line texttitle for each block used as the heading element s content i e h h h leadsingle line textshort text block that will be rendered above the heading tag in our application excerptsingle line textshort text block that will be rendered below the heading tag in our application contentlong textlong from content i e paragraph that will be rendered as a block of text mediaIdlinked recordused to link to related media for each block sectionIdlinked recordused to link to the section that will render this block mediafieldfield typedescriptiontitlesingle line textrepresents the title for each media item only used for reference purposes urlattachmentholds a file attachement as an object from which we use the url property altsingle line textused to populate the alt tag for each image blockIdlinked recordused to link to the block that will render each media item seoIdlinked recordcan be used to reference an image from the seo table to be used as the og image for each page seofieldfield typedescriptiontitlesingle line textused to populate the title tag for each page descriptionsingle line textused to populate the description tag keywordssingle line textused to populate the keywords tag sitenamelinked recordused to populate the site name tag urllinked recordused to populate the site url tag pageIdlinked recordused to reference the page that each SEO record belongs to mediaIdlinked recordused to link to related media to be used as the og image for each page RelationshipsSince one of the pre requisites of this post was an understanding of relational databases we won t dive too deep into the following concept of relationships In the diagram above you can see each table along with each of its fields and corresponding field types You can also get a rough idea about how some of the fields are used to link data from different tables together At its core Airtable is a relational database The platform abstracts away a lot of the relational complexity and provides an easy to use interface that resembles a spreadsheet instead Under the hood relational concepts such as the use of primary and foreign keys are implemented to link records of your Airtable base to one another across your different tables Airtable calls these types of fields linked records but these types of records behave similarly to the way foreign keys are implemented in relational databases If you re not familiar with these relational database terms I advise taking a quick second to skim through the introduction of this article And also more about linked records in Airtable In Airtable the first field in each table acts similar to a primary key Airtable calls these fields the primary field In your Airtable base the first field on each table is the title field which essentially functions as the primary reference to the record it represents The contents of each primary field field get indexed by Airtable which means we can search for our records by their title ️NOTE It s good practice to make sure the field that is used as the primary key for each table has a unique value although Airtable does not enforce this constraint More about Airtable primary keysNaming ConventionWe have adopted a simple naming convention from relational databases for the naming of each of the foreign key fields where the field is named as a combination foreign tablename Id For example on the sections table the pageId field links to a page record so it s aptly named pageId This naming convention helps us address a disparity between how the Airtable UI presents data for linked records as a list of titles in our Airtable base versus how the API represents this same data as an array of unique ids Airtable API RelationshipsLet s dig a bit further at the difference between how data looks in the Airtable UI versus in the Airtable API using a small chunk of the data in your new Airtable base The API response snippet shown below for the sectionId field returns an array of ids Each id in the array represents a linked record Airtable response for the sectionId field sectionId recTiTyzYFdayHJs recmiacYCQPuIseY recnJxlcmVYWeu But in the Airtable UI these same linked records appear as the sectionId Ultimately this behavior in the API makes sense Matching and looking up IDs is better than working with ever changing strings Relationships can sometimes be tricky to reason about but we re not doing anything complex here As long as you have a general understanding of the basics you should feel confident enough to proceed Next js Setup Starter overviewThe starter repo is a boilerplate create next app with a single dependency added airtable js All the styles needed for the entire project are included with the starter as CSS modules all located in the styles directory There are a couple of pre fabricated presentational components and a few helper methods also included with the starter repo We ll go over each in a bit of detail but first let s set up the application Clone the starter repo locally git clone Add credentialsNow add your Airtable credentials as environment variables to your local repository With Next js you can simply create a file called env local at the root of your project Next js adds this file to your gitignore by default and securely injects the variables into your environment at build time More about Next js Environment Variables env localAIRTABLE API KEY YOUR AIRTABLE API KEY HERE AIRTABLE BASE ID YOUR AIRTABLE BASE ID HERE Now that you have your application credentials configured go ahead and start your development server to make sure everything is working for you yarn devNow navigate to http localhost You should see the welcome message shown below And there you have it Your Next js application is now running locally and you ve got your environment variables configured The next thing you ll want to do is configure your Airtable base to work with your Next js application but before we get there let s take a moment to go over the structure of your Airtable base and how it will work as a CMS Integrate AirtableNow connect your Airtable base to your Next js app You already have airtable js included as a dependency in the package json file of your Next js application So we can jump right in and begin by instantiating an instance of Airtable in our project lib airtable jsconst Airtable require airtable const getMinifiedRecords minifyRecord require utils airtable airtable queries are based on views export const VIEW Grid view instantiate airtableexport const table new Airtable apiKey process env AIRTABLE API KEY create reference to airtable baseexport const base table base process env AIRTABLE BASE ID Even though airtable js provides a very easy to use wrapper around the Airtable REST API working with Airtable data on the client side can be a bit of a clunky process To make querying the API easier your starter includes several helper functions These functions are used to help you interact with the API and make data handling a bit more manageable lib airtable js Airtable query helpersexport const getPage async page launch table pages options view VIEW gt creates a filter allowing your to query your records by searching for matching title values const filterByFormula AND title page const records await base table select filterByFormula options all return getMinifiedRecords records export const getRecordById async table id gt const record await base table find id return minifyRecord record export const getRelatedRecords async table ids gt const records await ids map async id gt const record await getRecordById table id return record return Promise all records getPage is a helper function that hard codes some default logic that you ll need for your queries i e table page and provides the ability to pass in any additional options This allows you to keep your logic extensible We also make use of the filterByFormula option to target and select the data we need to render the launch page getRecordById is used to query a single record by its id getRelatedRecords is a function that takes in an array of ids The function calls getRecordById for each id in the array and returns the results as a single array of records Notice the helpers we defined reference two other utility functions getMinifiedRecords and minifyRecord These functions do not interact with the Airtable API themselves but are instead used to transform your Airtable records into data that is more manageable on the client side utils airtable js maps over the records calling minifyRecord giving us required dataexport const getMinifiedRecords records gt if Array isArray records return minifyRecord records return records map record gt minifyRecord record gets the data we want and puts it into variables we can referenceexport const minifyRecord record gt return id record id fields record fields minifyRecord takes a record from an Airtable response and only returns the data we need for our application It strips away any helper methods and utility functions that are generally included on the response object by airtable js getMinifiedRecords takes an array of Airtable response records and calls minifyRecord for each one before returning the results With Airtable instantiated and your helper functions in place you can turn your attention to using these helpers to fetch your Airtable data and use it to render static a page Next js Data FetchingNext js supports several data fetching strategies out of the box In this post we ll be focusing on getStaticProps which is how we create optimized static pages in Next js Static Site Generation SSG getStaticProps provides a way for you to query the file system or any external resources during the build process This means its logic can be executed on the server at build time in your production environment and on each page load in your local development environment getStaticProps is an asynchronous function that can be exported from any top level page component Next js will automatically execute this function at build time before generating the static page More about getStaticProps ️In development you can always trigger a re fetch with getStaticProps by refreshing the page but in production you ll have to redeploy the application either manually from your hosting console or with a deploy hook ️NOTE Next js offers two additional data fetching strategies incremental static regeneration ISR and traditional server side rendering SSR Any of these features including static site generation SSG can be implemented on a per page basis This allows us as the developers to choose which strategy is right for each use case For more about each strategy I highly recommend this article Now that you have an idea of what getStaticProps can do let s put it to work and use it to query data from your Airtable base pages index jsimport Head from next head import styles from styles Home module css export async function getStaticProps asynchronously import neccessary modules so we can avoid any client side compilation const getPage getRecordById getRelatedRecords await import lib airtable query inital data from airtable const launch await getPage launch get related seo metadata if launch fields seoId length const seo await getRelatedRecords seo launch fields seoId if seo fields mediaId length get related media for seo og image const ogImage await getRecordById media seo fields mediaId seo fields ogImage ogImage launch seo seo return props page launch id launch export default function Home page return lt div className styles container gt lt Head gt lt title gt Create Next App lt title gt lt link rel icon href favicon ico gt lt Head gt lt main className styles main gt lt h className styles title gt Welcome to lt a href gt Next js lt a gt lt h gt lt div className styles card gt JSON stringify page null lt div gt lt main gt lt div gt As you can see we re only fetching a subset of our data and dumping it directly onto the page just to make sure everything is wired up properly You should see your data dumped to the page as shown below It may not seem like it but a lot of our logic is being handled by getStaticProps so let s go over it step by step We first import any modules we need asynchronously inside of getStaticProps this is a neat way to ensure that all of this logic only runs on the server at build time asynchronously import neccessary modules and avoid any client side evaluationconst getPage getRecordById getRelatedRecords await import lib airtable Then we query Airtable for the launch page data using the getPage helper function query inital data from airtableconst launch await getPage launch Which amongst the rest of the data returns an array of ids for the seoId field In this case the array contains a single id linking to the seo table and pointing to the record with the title Uptime Monitoring Take a look at the image below as a refresher for how pages table is related to the seo table Recall that the title field shown above in the UI is represented as an id in the API response The API response automatically substitutes the title value in linked records with unique ids instead We can use the seoId array to help us query Airtable once more for the related SEO record for your launch page get related seo metadataif launch fields seoId length const seo await getRelatedRecords seo launch fields seoId if seo fields mediaId length get related media for seo og image const ogImage await getRecordById media seo fields mediaId seo fields ogImage ogImage launch seo seo We use the seoId array to fetch the related meta data for the launch page from the seo table We also check if any media image exists so that we can use it as the og image for the launch page Once we have our data we can return the entire page object as a prop from getStaticProps which contains all of the related records from each of our responses return props page launch id launch Lastly we access the page prop from our component and dump our data onto the page as JSON export default function Home page return lt div className styles container gt lt Head gt lt title gt Create Next App lt title gt lt link rel icon href favicon ico gt lt Head gt lt main className styles main gt lt h className styles title gt Welcome to lt a href gt Next js lt a gt lt h gt lt div className styles card gt JSON stringify page null lt div gt lt main gt lt div gt Now that you understand how we re able to fetch data from Airtable with Next js using getStaticProps let s take a look at how that data correlates to the structure of your application The diagram below illustrates how each of the fields from your SEO table can be mapped to the corresponding meta tag in your application s HTML markup This allows you to make changes in your Airtable base and directly update the structure of your markup resembling the functionality of a CMS ️Remember In development you will see new updates from your Airtable base with each page refresh but in production you ll need to rebuild and deploy your application in order to see any changes take effect Now that you have an idea of how we ll use the data from your Airtable base as a CMS to render out the initial structure of your application we can turn our attention back to getting the rest of the related data you ll need to fully build out the Splash page We re going to do the same thing we did above to get the related SEO data but we ll have to make several round trips to the Airtable API in order to get all of the data we need First we ll need to query for all of the sections needed to render the launch page Then we can iterate over each section to get the related blocks for each section And while we re iterating we ll need to do the same for any media image related to each block We essentially return each responses all while building up the final page object we ll use to render the application All of this logic will be handled within getStaticProps Similar to the way we queried for the SEO metadata pages index jsexport async function getStaticProps asynchronously import neccessary modules and avoid any client side evaluation const getPage getRecordById getRelatedRecords await import lib airtable query inital data from airtable const launch await getPage launch get related seo metadata if launch fields seoId length const seo await getRelatedRecords seo launch fields seoId if seo fields mediaId length get related media for seo og image const ogImage await getRecordById media seo fields mediaId seo fields ogImage ogImage launch seo seo get related data if there is any if launch fields sectionId length const sections await getRelatedRecords sections launch fields sectionId get all blocks for each section and their related media if sections length launch sections await Promise all await sections map async section gt if section fields blockId length const blocks await getRelatedRecords blocks section fields blockId if blocks length section blocks await Promise all await blocks map async block gt if block fields mediaId length const media await getRelatedRecords media block fields mediaId if media length block media media return block return section return props page launch id launch ️NOTE that once again we rely on the array of ids we get back from each of the linked record fields to then request each related record by id With this in place you should now be seeing even more data being dumped onto your page as shown in the image below Rendering Data From AirtableNow that you already have all of your data dumped on the client side of your application you can style and present it however you want to For this project the starter comes with several pre fabricated components that you can use to render this data Let s take a look at how these components fit together to make up the structure of your application UI As you can see from the diagram above our index page renders the Splash component which in turn is responsible for rendering each of the sections in your Splash page Each section from your Airtable base maps to a component in your application We use the type field to determine which component renders each section The image below shows an example of the mapping between your Airtable fields and the markup used to render them with the Hero component The first component your Splash component is responsible for rendering is the Hero component components Hero jsimport styles from styles Hero module css import Image from next image export const Hero data gt return lt div className styles hero gt lt div className styles heroContent gt lt p className styles lead gt data fields lead lt p gt lt h className styles heading gt data fields title lt h gt lt p className styles excerpt gt data fields excerpt lt p gt lt div gt data media length amp amp lt div className styles heroImage gt lt Image layout intrinsic src data media fields url url alt data media fields alt objectFit fill width height gt lt div gt lt div gt The Hero component simply renders a column responsive flexbox layout If you ll look closely at the markup you ll see that the hero component only accepts thelead heading and excerpt fields from your blocks table It is not templated to render a content field It will also render the related media image as well You can take a look at the styles we use to achieve this layout in styles Hero module css ️REMINDER All of the styles for each of the components included with the starter can be found in the styles directory Next js Image SupportNext js recently introduced some really powerful image optimizations with their built in Image component One of the features we are using for the Hero component above is the layout prop with a value of intrinsic which simply tells Next js to optimize this image with some basic responsiveness More on Next js Image Props ️NOTE There is a caveat the Next js image component works well out of the box with any images saved locally as an asset in your project to the public directory otherwise it needs us to define a domain for any external images so that it understands which domains to optimize for This is done by extending the default next js webpack configuration via a next config js file Under the hood Next js will execute file this during the build process and optimize your package bundle with responsive variations of your image next config jsmodule exports images domains dl airtable com With this in place Next js will know to optimize images from this domain You can also list multiple domains if you re using several resources for image handling️NOTE Your local server will need to be restarted after any changes to your next config js file Next we have a List component that is used to render out a list of benefits with icons corresponding to each benefit components List jsimport Image from next image import styles from styles List module css export const List data rest gt return lt ul className styles list gt data map block gt lt ListItem key block id className styles listItem img block media fields rest gt block fields title lt ListItem gt lt ul gt export const ListItem img filter children gt return lt li className styles listItem gt filter includes withIcons amp amp lt span className styles icon gt lt Image layout intrinsic src img url url alt img alt width px height px gt lt span gt children lt li gt You ll also notice that we re rendering a ListItem for each benefit which includes an icon and some text for each Each benefit is represented as its own block in AIrtable so we have to iterate over them to render each one out The next component we ll need is the Cta component which simply renders a standard signup form for updates regarding your launch components Cta jsimport styles from styles Cta module css export const Cta data filter gt const handleSubmit e gt e preventDefault const input e target querySelector input console log input value return lt div className styles cta gt data map block gt lt div key block id gt lt h gt block fields title lt h gt lt p gt block fields excerpt lt p gt filter includes withForm amp amp lt form onSubmit handleSubmit gt lt div className styles inputGroup gt lt input type email placeholder you youremail com required className styles input gt lt div className styles inputRight gt lt button type submit className styles submit gt Sign up now lt button gt lt div gt lt div gt lt form gt lt div gt lt div gt Although you have a bit more logic in this component it s still quite simple The component uses the filter field as a modifier to conditionally render a form This helps us keep the Cta component extendable and reusable with several variations that can be applied from your Airtable response For our use case the form simply prints the data out to the console but you could just as easily send the data to a mailing list provider or other external resources The last component we ll need is the Splash component This component iterates over the page s sections array and renders the appropriate section with the corresponding component components Splash jsimport Container Wrapper Row from Containers import Hero from Hero import List from List import Cta from Cta const components list List cta Cta export const Splash data gt if Array isArray data return null const hero restComponents data return lt Wrapper gt lt Container gt hero amp amp lt Hero key hero id data hero blocks filter hero fields filter gt lt Row gt restComponents map section gt const Component components section fields type if section fields type includes list return lt Component key section id section order data section blocks filter section fields filter gt if section fields type includes cta return lt Component key section id section order data section blocks filter section fields filter gt return null lt Row gt lt Container gt lt Wrapper gt The Splash component gives us some control over which components are used to render each section of our Airtable data We use the type field to define the component that is used to render this section and the filter field to further add granular control by allowing conditional rendering logic There s one final thing left to do You ll need to render the entire Splash component from pages index js pages index jsimport Head from next head import Splash from components Splash import styles from styles Home module css export default function Home page console log return lt div className styles pageWrapper gt lt Head gt lt title gt page seo fields title lt title gt lt meta name viewport content initial scale width device width gt lt meta name description content page seo fields description gt lt meta property og title content page seo fields title gt lt meta property og site name content page seo fields sitename gt lt meta property og url content page seo fields url gt lt meta property og description content page seo fields description gt lt meta property og image content page seo fields ogImage fields url url gt lt link rel icon href favicon ico gt lt link rel cannonical href page seo fields url gt lt Head gt lt main className styles main gt lt Splash data page sections gt lt main gt lt div gt All you have to do pass down your Airtable sections array into the Splash component as props and it handles the rest Also Note We ve also implemented search engine optimization using data from our Airtable seo table This is just a basic implementation and if you re looking for a more robust solution I highly recommend using next seo for projects that need a more extensible SEO implementation SummaryThat s it for the first part of the series I imagine this was a lot to take in but let s take a quick look at how far we ve come in just the first part of our series So far you ve learned how to implement a custom CMS for your Splash page using Airtable You also got a close look at how Next js gives you the ability to perform server side operations even with static pages at build time making it a great choice for this use case And we also covered how you can use Next js for some really simple image optimization Next StepsYou ve already accomplished a lot already but I would advise opening up your Airtable base and from the blocks table start to edit some of your content You should be able to see your changes reflected in your application after each page load just like you would with any CMS Next I d suggest playing around with the application and and adding a new section to it Something like a founder s message seems like a good fit In the next part of this series we ll go even further and take a look at how we can use Sync Inc to synchronize our Airtable base with a cloud Postgres instance This not only gives your application enterprise grade scalability but also opens your application up to tons of possibilities including the ability to query your Airtable data with the power and flexibility of raw SQL queries So join me for the next installment and be sure to follow me on twitter soham asmi to stay up to date with my latest posts and reach out to me with any feedback or questions Until next the next one |
2021-06-14 14:06:49 |
海外TECH |
DEV Community |
JavaScript Interview Question #47: How Object.setPrototypeOf works in JS |
https://dev.to/coderslang/javascript-interview-question-47-how-object-setprototypeof-works-in-js-564j
|
JavaScript Interview Question How Object setPrototypeOf works in JSWhat is Object setPrototypeOf in JavaScript How does it work What s the output TheoryThe function Object setPrototypeOf sets the new prototype for any JavaScript object The object itself doesn t change but it inherits the behavior of the object used in setPrototype You can check it by accessing the proto property before modifying the prototype and after it For example let s create an object with a single field name and and an array with elements const user name John const arr console log Original state console log user name John console log user undefinedconsole log user proto console log user length undefinedObject setPrototypeOf user arr добавляемпрототипarr кuserconsole log Modified state console log user Array name John console log user console log user proto console log user length After modifying the prototype of the user we got access to the parent field length and inherited the elements of the array arr Now we can access them by index PracticeIn our original code snippet happens the same The user object gets access to the field name from the object of a type Human but it won t get any new fields The function Object keys returns an array formed by all the fields that the object has But not the inherited ones As the user object doesn t have any own properties the length of this array is ANSWER The first console log prints an empty array to the screen and the second one prints the string John Learn Full Stack JavaScript |
2021-06-14 14:01:31 |
海外TECH |
DEV Community |
Writing a graphQL fullstack Svelte Web App with Sapper & Postgraphile |
https://dev.to/gevera/writing-a-graphql-fullstack-svelte-web-app-with-sapper-postgraphile-1npa
|
Writing a graphQL fullstack Svelte Web App with Sapper amp Postgraphile Writing a graphQL fullstack Svelte Web App with Sapper amp PostgraphileFinally I ve got some free time for writing so today I would like to share with you a simple yet powerfull way to write full stack web apps using my favorite tools Sapper SveltePostgres SQLPostgraphile graphQLA friend of mine asked me if I could help him with some boring paperwork stuff by creating a internal CRM for his medical office I ve decided to give it a shot You can check the repo and see the internals if you don t have time for lenghy explanation or if you are intersted in details read on The project consists of a client list with personal data like dob telephone etc and also a monthly medical intake data for each client like WBC RBC HBG HCT etc PostgresFirst thing first we will start with creating a database in Postgres and defining tables for our usecase sudo u postgres psqlCREATE USER admin WITH PASSWORD adminpassword CREATE DATABASE medical db OWNER admin c medical db admin localhost CREATE TABLE clients client id SERIAL PRIMARY KEY first name text NOT NULL last name text NOT NULL telephone text NOT NULL UNIQUE gender varchar NOT NULL CHECK gender IN MALE FEMALE active boolean NOT NULL DEFAULT TRUE dob date NOT NULL CREATE TABLE intake intake id SERIAL PRIMARY KEY client id INTEGER NOT NULL REFERENCES clients client id weight decimal NOT NULL wbc decimal NOT NULL rbc decimal NOT NULL hbg decimal NOT NULL hct decimal NOT NULL CHECK hct gt AND hct lt intake time timestamp DEFAULT now If you dont know SQL it is a shame Even though it might not seem to be as fancy or cool like modern day ORMs don t be decieved because SQL is very very powerfull language The fact is the ORMs are not even close to all the capabilities of SQL Learn it It can do magic Setting up SapperNow let s move on and create the basis for our Sapper app npx degit sveltejs sapper template rollup medical appcd medical appnpm installWe have just set up the default project It comes with some boilerplate stuff that we won t need Get rid of all the default styles in static src global cssAlso delete all the files that are in src routes and src components folders Now we won t style the project ourself Will let this little file do it for us lt link rel stylesheet href gt Just ad this to the head of the src template html fileMVP css is a minimalist CSS framework no class names at all I usually use it to save time for quick prototype styling I like it for it s simplicity and elegant design Setting up PostgraphileGreat Now here comes my favorite part Postgraphile This thing is a beast in itself and I totally recommend checking it out What Postgraphile actually does it reads the definition of the tables that we have created previously and creates automagicaly queries and mutations so we don t have to write them manualy ourselves Isn t that cool Besides that it provides us with a frontend UI that we will use later to check our queries It is battle tested piece of software and has a very welcoming and great team behind it Let s install Postgraphilenpm i postgraphileFor queries and mutations I use awesome urql client for Svelte It is light and intuitive to work with npm i D urql svelte graphql In order to make postgraphile work import into the src server js fileimport postgraphile from postgraphile and add Postgraphile as middleware for polka polka use postgraphile process env DATABASE URL postgres admin adminpassword localhost medical db public watchPg true graphiql true enhanceGraphiql true compression threshold That s it Testing PostgraphileNow if you start the server withnpm run devand visit the localhost graphiql route you sould be greeted with a graphiql a web interface for queries and mutations that we talked about earlier Let s make sure queries and mutations are working properly We will fetch some non existent clients query MyQuery allClients nodes firstName lastName clientId nodeId telephone dob Abviously the result is an empty array since we haven t added any clients yet Let s quickly add one Fetch it again and voila We got a graphql server working on Sapper with very little work The only thing is left now is to create some interface so we can interact with our database using graphQL and lovely Svelte Svelte amp graphQL with urql svelteWe do not have any routes yet and no layout for them So let s make some I have created the following routes index svelte clients newclient svelte clients slug index svelte clients slug intakes newintake svelte clients slug intakes slug svelteAlso in the src routes folder we need a layout svelte file with a slot wrapped in the main tags lt script gt import Nav from components Nav svelte import createClient setClient fetchExchange from urql svelte const client createClient url http localhost graphql exchanges fetchExchange setClient client lt script gt lt Nav gt lt main gt lt slot gt lt slot gt lt main gt and the Nav svelte in the components folder lt nav gt lt ul gt lt li gt lt a href gt Clients lt a gt lt li gt lt li gt lt a href clients newclient gt Add a client lt a gt lt li gt lt li gt lt a href graphiql gt Postgraphile lt a gt lt li gt lt ul gt lt nav gt Notice that we have also initialized the urql svelte client pointing to our Postgraphile graphql endpoint in the layout page so we can access it from any route The main index svelte lt script gt import operationStore query from urql svelte import ClientsTable from components ClientsTable svelte const clients operationStore query MyQuery allClients nodes clientId firstName lastName active telephone intakesByClientId totalCount requestPolicy cache first query clients const refresh gt clients context requestPolicy network only lt script gt lt svelte head gt lt title gt Postgraphile Clients lt title gt lt svelte head gt lt section gt lt header gt lt h gt Client List lt h gt lt button on click refresh gt refresh lt button gt lt header gt if clients fetching lt h gt Loading lt h gt else if clients error lt h gt Oh no clients error message lt h gt else lt ClientsTable clients clients data allClients nodes gt if lt section gt Creating a form for new clientIn clients newclient svelte lets import a component with a form for client creation lt script gt import ClientForm from components ClientForm svelte lt script gt lt ClientForm gt And here is the actual component lt script gt import mutation from urql svelte import onMount from svelte import goto from sapper app const createClientMutation mutation query mutation MyMutationCreate firstName String lastName String telephone String gender String dob Date active Boolean createClient input client firstName firstName lastName lastName telephone telephone gender gender dob dob active active client firstName lastName telephone nodeId clientId active const updateClientMutation mutation query mutation MyMutationUpdate id Int firstName String lastName String telephone String gender String dob Date active Boolean updateClientByClientId input clientPatch active active clientId id dob dob gender gender firstName firstName lastName lastName telephone telephone clientId id client firstName lastName let clt firstName lastName telephone dob gender active true export let originalClient const createNewClient async gt const responseCreate await createClientMutation clt dob new Date clt dob console log responseCreate if responseUpdate data goto const updateClient async gt const responseUpdate await updateClientMutation clt id originalClient clientId dob new Date clt dob console log responseUpdate if responseUpdate data goto const handleClient async gt originalClient updateClient createNewClient onMount gt if originalClient clt Object assign originalClient lt script gt lt section gt lt form on submit preventDefault handleClient gt lt div class grd gt lt label for fistName gt First Name lt input type text name firstName required bind value clt firstName gt lt label gt lt label for lastName gt Last Name lt input type text name lastName required bind value clt lastName gt lt label gt lt label for telephone gt Telephone lt input type tel name telephone required bind value clt telephone gt lt label gt lt label for dob gt Date of Birth lt input type date name dob required bind value clt dob gt lt label gt lt label for gender gt Gender lt select name gender required bind value clt gender gt lt option value disabled selected gt lt option gt lt option value MALE gt Male lt option gt lt option value FEMALE gt Female lt option gt lt select gt lt label gt lt label for active gt Active lt input type checkbox bind checked clt active gt lt label gt lt div gt lt br gt if originalClient lt button type submit gt Update client lt button gt else lt button type submit gt Add client lt button gt if lt form gt lt section gt lt style gt grd display grid grid template columns fr fr lt style gt If you pay attention we have here to mutaions create and update client This is because we are reusing the same form for both cases Add the table of clientsHere is ClientsTable svelte component that we are importing in the main index svelte We are expecting an array of clients We loop thru it via each clients as client and display desired data lt script gt export let clients lt script gt lt table gt lt tr gt lt th gt Name lt th gt lt th gt Status lt th gt lt th gt Phone number lt th gt lt th gt Intakes lt th gt lt th gt lt tr gt each clients as client client clientId lt tr gt lt td gt client firstName client lastName lt td gt lt td gt client active ACTIVE INACTIVE lt td gt lt td gt lt a href tel client telephone gt client telephone lt a gt lt td gt lt td gt client intakesByClientId totalCount lt td gt lt td gt lt a href clients client clientId gt lt button gt More lt button gt lt a gt lt td gt lt tr gt each lt table gt lt style gt table margin auto lt style gt Edit Slug page of a client lt script gt import ClientForm from components ClientForm svelte import stores from sapper app const page stores import operationStore query from urql svelte import onMount from svelte import IntakeTable from components IntakeTable svelte const client operationStore query MyQuery id Int clientByClientId clientId id firstName lastName dob gender telephone active clientId intakesByClientId nodes intakeId intakeTime rbc id parseInt page params slug requestPolicy cache first query client const refresh gt client context requestPolicy network only onMount gt refresh clientIntakes client data clientByClientId intakesByClientId nodes lt script gt lt div class rght gt lt a href clients page params slug intakes newintake gt lt button gt New Intake lt button gt lt a gt lt div gt if client fetching lt h gt Loading lt h gt else if client error lt h gt Oh no client error message lt h gt else lt div class flx gt lt ClientForm originalClient client data clientByClientId gt lt IntakeTable clientIntakes clientId page params slug gt lt div gt if lt style gt rght text align right lt style gt We are reusing the ClientForm for editing Notice how we pass the slug into the client query as id New form for medical data inputIn our newintake route we are adding IntakeForm svelte component and pass to it the clientId from page params slughere is the component itself lt script gt import mutation from urql svelte import goto from sapper app export let clientId let intakeData wbc rbc hbg hct weight const createIntakeMutation mutation query mutation MyMutation id Int wbc BigFloat rbc BigFloat hbg BigFloat hct BigFloat weight BigFloat createIntake input intake clientId id wbc wbc rbc rbc hbg hbg hct hct weight weight intake intakeId const createNewIntake async gt const responseCreate await createIntakeMutation id parseInt clientId intakeData console log responseCreate if responseCreate data goto clients clientId lt script gt lt section gt lt h gt New Intake lt h gt lt form on submit preventDefault createNewIntake gt lt label for wbc gt White blood cells lt input type number name wbc step required bind value intakeData wbc gt lt label gt lt label for rbc gt Red blood cells lt input type number name rbc step required bind value intakeData rbc gt lt label gt lt label for hbg gt HBG lt input type number name hbg step required bind value intakeData hbg gt lt label gt lt label for hct gt HCT lt input type number name hct required step bind value intakeData hct min max gt lt label gt lt label for weight gt Weight lt input type number step name weight bind value intakeData weight gt lt label gt lt button type submit gt Send lt button gt lt form gt lt section gt lt style gt section display flex flex direction column gap rem justify content center align items center lt style gt It is intersting to note that the mutation here for the variables is set to BigInt since we defined them in the intake schema as decimal We have set the input to step And that is it I hope you have learned something new If you have any suggestions and know how to improve the code please hit me up I will be glad to hear from you It was quite easy to make a complete full stack app with Sapper Postgraphile here does the whole magic under the hood I would like to thank Bengie for it Cheers |
2021-06-14 14:01:26 |
Apple |
AppleInsider - Frontpage News |
WWDC HomeKit changes, new product launches, & listener questions on HomeKit Insider |
https://appleinsider.com/articles/21/06/14/wwdc-homekit-changes-new-product-launches-listener-questions-on-homekit-insider?utm_medium=rss
|
WWDC HomeKit changes new product launches amp listener questions on HomeKit InsiderOn this week s episode of HomeKit Insider we talk about all the news for the week including the bonanza from WWDC and answer a few listener questions We saw a pair of product launches for the week notably HomeKit arriving on the Sensibo Pure air purifier making it the fourth HomeKit enabled air purifier after Molekule SmartMi and VOCOlinc Aqara also brought its M hub to the US with several improvements over the original such as a hardwired Ethernet connection and an improved design that no longer protrudes from the wall and blocks the adjacent outlet Andrew has already written much about what s new with HomeKit in Apple s forthcoming update but we break it down for this episode of the podcast Stephen explains his favorite new features while Andrew touches on his as well Read more |
2021-06-14 14:24:40 |
Apple |
AppleInsider - Frontpage News |
New Apple Music ad visualizes Spatial Audio with cloned singers |
https://appleinsider.com/articles/21/06/14/new-apple-music-ad-visualizes-spatial-audio-with-cloned-singers?utm_medium=rss
|
New Apple Music ad visualizes Spatial Audio with cloned singersApple has created a new ad to promote the new Spatial Audio and Dolby Atmos feature of Apple Music as being Beyond Stereo for its listeners Apple s Spatial Audio spot for Apple Music Published to YouTube on Monday the video titled Introducing Spatial Audio on Apple Music Beyond Stereo offers a visual representation of the new D audio feature Read more |
2021-06-14 14:06:12 |
Apple |
AppleInsider - Frontpage News |
Amazon Prime Luna cloud gaming service available for Mac, iOS on June 21 |
https://appleinsider.com/articles/21/06/14/amazon-prime-luna-cloud-gaming-service-available-for-mac-ios-on-june-21?utm_medium=rss
|
Amazon Prime Luna cloud gaming service available for Mac iOS on June Amazon will open access to its Luna cloud game streaming platform on June and June allowing anyone with an Amazon Prime account to test out the service Credit AmazonCustomers will be able to nab a seven day free trial to Luna on Amazon Prime Day June and June Although the offer itself is time limited users can opt to keep their subscriptions active after the trial ends Previously access to Luna was given out on an invite only basis on Amazon Fire TV devices Read more |
2021-06-14 14:05:25 |
海外TECH |
Engadget |
This $60 training package can give you a headstart learning Python |
https://www.engadget.com/python-training-bundle-145509171.html?src=rss_b2c
|
This training package can give you a headstart learning PythonThe Complete Python Expert Super Bundle has nearly hours of content that will help beginners get experience in a versatile coding language |
2021-06-14 14:55:09 |
海外TECH |
Engadget |
Niantic and Hasbro are making a Transformers AR game |
https://www.engadget.com/niantic-hasbro-transformers-heavy-metal-ar-game-144544180.html?src=rss_b2c
|
transformers |
2021-06-14 14:45:44 |
海外TECH |
Engadget |
‘Welcome to Elk’ packs an emotional wallop in its short play time |
https://www.engadget.com/welcome-to-elk-gaming-irl-143006731.html?src=rss_b2c
|
personal |
2021-06-14 14:30:06 |
海外TECH |
Engadget |
'The Morning Show' season 2 trailer reveals turmoil at the anchor desk |
https://www.engadget.com/the-morning-show-season-2-teaser-apple-tv-plus-141241307.html?src=rss_b2c
|
x The Morning Show x season trailer reveals turmoil at the anchor deskApple is premiering The Morning Show season on September th and the teaser trailer shows the turmoil that follows Alex and Bradley s decisions |
2021-06-14 14:12:41 |
海外科学 |
NYT > Science |
How the Virus Unraveled Hispanic American Families |
https://www.nytimes.com/2021/06/14/health/coronavirus-hispanic-california.html
|
hispanic |
2021-06-14 14:42:52 |
海外科学 |
NYT > Science |
Shi Zhengli, Chinese Virologist, Faces Scrutiny Over Wuhan Lab Research |
https://www.nytimes.com/2021/06/14/world/asia/china-wuhan-lab-leak.html
|
Shi Zhengli Chinese Virologist Faces Scrutiny Over Wuhan Lab ResearchShi Zhengli a top virologist said in a rare interview that speculation about her lab in Wuhan was baseless But China s habitual secrecy makes her claims hard to validate |
2021-06-14 14:21:04 |
金融 |
RSS FILE - 日本証券業協会 |
本協会次期会長の決定及び定時総会の結果報告について |
https://www.jsda.or.jp/about/houdou/2021/20210614.html
|
定時総会 |
2021-06-14 15:00:00 |
金融 |
RSS FILE - 日本証券業協会 |
新型コロナウイルス感染症への証券関係機関等・各証券会社の対応について(リンク集) |
https://www.jsda.or.jp/shinchaku/coronavirus/link.html
|
新型コロナウイルス |
2021-06-14 14:40:00 |
金融 |
RSS FILE - 日本証券業協会 |
J-IRISS |
https://www.jsda.or.jp/anshin/j-iriss/index.html
|
iriss |
2021-06-14 14:33:00 |
ニュース |
BBC News - Home |
No evidence Bashir rehired as cover-up - BBC report |
https://www.bbc.co.uk/news/uk-57469980
|
bashir |
2021-06-14 14:40:24 |
ニュース |
BBC News - Home |
Arlene Foster urges NI parties to stick to language deal |
https://www.bbc.co.uk/news/uk-northern-ireland-57468751
|
arlene |
2021-06-14 14:28:26 |
ニュース |
BBC News - Home |
Nicky Campbell swaps BBC Radio 5 Live Breakfast for new phone-in show |
https://www.bbc.co.uk/news/entertainment-arts-57472944
|
breakfast |
2021-06-14 14:49:32 |
ニュース |
BBC News - Home |
Euro 2020: Patrik Schick scores amazing lob from half way |
https://www.bbc.co.uk/sport/av/football/57474374
|
scotland |
2021-06-14 14:21:41 |
ニュース |
BBC News - Home |
Euro 2020: Rate the players - Scotland v Czech Republic |
https://www.bbc.co.uk/sport/football/51198017
|
czech |
2021-06-14 14:03:55 |
ニュース |
BBC News - Home |
Euro 2020: Patrik Schick heads Czech Republic into lead against Scotland |
https://www.bbc.co.uk/sport/av/football/57473558
|
czech |
2021-06-14 14:05:45 |
ニュース |
BBC News - Home |
What are the social distancing rules and when could they end? |
https://www.bbc.co.uk/news/uk-51506729
|
will |
2021-06-14 14:47:43 |
ニュース |
BBC News - Home |
Christian Eriksen: Resuming Denmark-Finland match was 'least bad decision', says Martin Braithwaite |
https://www.bbc.co.uk/sport/football/57468439
|
Christian Eriksen Resuming Denmark Finland match was x least bad decision x says Martin BraithwaiteDenmark forward Martin Braithwaite says the decision to resume Denmark s Euro opener against Finland following Christian Eriksen s cardiac arrest was the least bad one |
2021-06-14 14:04:16 |
LifeHuck |
ライフハッカー[日本版] |
梅雨の自転車移動に役立つ! タイプ別レインコート3選 |
https://www.lifehacker.jp/2021/06/amazon-raincoat-3sen.html
|
送り迎え |
2021-06-14 23:30:00 |
コメント
コメントを投稿