python |
Pythonタグが付けられた新着投稿 - Qiita |
Enumを使って複数の定数文字列を管理する。 |
https://qiita.com/NMZ0429/items/c011a55c62a69f939995
|
nenumenumaabbccmychoiceo |
2022-10-16 05:09:01 |
海外TECH |
DEV Community |
SvelteKit Server-Side Rendering (SSR) with @urql/svelte |
https://dev.to/tiim/sveltekit-server-side-rendering-ssr-with-urqlsvelte-534k
|
SvelteKit Server Side Rendering SSR with urql svelteIn this blog post I will explain why server side rendering with the urql GraphQL library is not as straightforward to do with SvelteKit and how I solved this in my project anyway Server side rendering SSR is one of the great features of SvelteKit I will try to keep this blog post short and will therefore not explain what server side rendering is and why you should take advantage of it you really should If you want to know more about SSR you can take a look at this article A Deep Dive into Server Side Rendering SSR in JavaScript Background SSR in SvelteKitSvelteKit implements SSR by providing a load function for every layout and page component If a page or layout needs to perform some asynchronous operation this should be done inside of this load function SvelteKit executes this function asynchronously on the server side as well as on the client side and the return value of this function is assigned to the data prop of the associated component Usually this asynchronous operation is loading data from an external service like in the case of this blog post a GraphQL server You can of course load data directly in the component but SvelteKit will not wait for this to complete when doing SSR and the resulting HTML will not include the loaded data Background urql svelteThe urql library allows us to easily issue GraphQL queries and mutations Some of the functionality it has to make our lives easier include Reloading a query when a query variable changesReloading a query after a mutation that touches the same data as the queryWe want to keep these features even when using urql when doing SSR The ProblemWhen implementing SSR in my project I ran into two problems I couldn t find any documentation or any articles solving them so I decided to write down my solutions to those problems in this blog post Problem Svelte and urql ReactivityLet s say we have the following load function which executes a GraphQL query to load a list of red cars src routes car page js type import types PageLoad export function load event const client createClient url config url fetch event fetch const carColor red const cars client query carsQuery color carColor toPromise then c gt c data car return cars This example uses the urql method client query to start a query to get us a list of cars with a red colour The GraphQL query is not shown but the exact query is not important for this example The client gets a special fetch function from the event which has a few nice properties like preventing a second network request on the client side if that same request was just issued on the server side Since the query code is now located in the load function and not in a svelte component there is no way to easily change the carColor and have urql automatically reload the query The only way to change the variable is to set the value as a query parameter and read that from the event argument This however means that we have to refresh the whole page just to reload this query The other thing urql does for us reloading the query when we do a mutation on the same data will not work with the above code either The solution A query in the load function and a query in the componentTo fix those two drawbacks we have to add the same query as in the load function to our component code as well Unfortunately this means when a user loads the page it sends a request from the client side even though the same request got sent from the server side already I created a small wrapper function queryStoreInitialData that creates the query inside of the component and intelligently switches from the possibly stale data from the load function to the new data Using this wrapper the page or layout might look as follows lt script gt import queryStoreInitialData from lib gql client The helper function mentioned above import getContextClient from urql svelte import carsQuery from query The query export let data gqlStore queryStoreInitialData client getContextClient query carsQuery data cars cars gqlStore data car lt script gt lt div gt lt pre gt JSON stringify cars null lt pre gt lt div gt The native queryStore function gets replaced with the wrapper function The initial value of the query is supplied to the wrapperUnfortunately we can not return the query result from the load function directly like this const result await client query cars toPromise return cars toInitialValue result This results in the following error Cannot stringify a function data events operation context fetch Error Cannot stringify a function data events operation context fetch at render response file app node modules sveltejs kit src runtime server page render js at runMicrotasks lt anonymous gt at processTicksAndRejections node internal process task queues at async render page file app node modules sveltejs kit src runtime server page index js at async resolve file app node modules sveltejs kit src runtime server index js at async respond file app node modules sveltejs kit src runtime server index js at async file app node modules sveltejs kit src exports vite dev index js This is because the query result contains data that is not serializable To fix this I created the toInitialValue function which deletes all non serializable elements from the result The load function now looks like follows src routes car page jsimport createServerClient toInitialValue from lib gql client import parse from cookie import carsQuery from query type import types PageServerLoad export const load async event gt const client createClient url config url fetch event fetch const result await client query cars toPromise return cars toInitialValue result Problem AuthenticationWe will look at the same load function as Problem Svelte and urql Reactivity the function creates a urql client with the fetch function from the event object and uses this client to send a query Sometimes however the GraphQL API requires authentication in the form of a cookie to allow access Unfortunately the fetch function that we get from the load event will only pass the cookies on if the requested domain is the same as the base domain or a more specific subdomain of it This means if your SvelteKit site runs on example com and your GraphQL server runs on gql example com then the cookies will get forwarded and everything is fine This however is in my experience often not the case Either you might use an external service for your GraphQL API or you host it yourself and want to use its internal domain The only way to pass the cookies on to the GraphQL server in this case is by manually setting the cookie header when creating the urql client This however forces us to use the server only load function as we do not have access to the cookie header in the normal load function The new code now looks like this src routes car page server js type import types PageServerLoad export function load event const client createClient url config url fetch fetchOptions credentials include headers inject the cookie header FIXME change the cookie name Cookie gql session event cookies get gql session const cars client query carsQuery toPromise return cars toInitialValue result To keep the size of the load functions across my codebase smaller I created a small wrapper function createServerClient src routes car page server js type import types PageServerLoad export function load event const client createServerClient event cookies const cars client query carsQuery toPromise return cars toInitialValue result The CodeBelow you can find the three functions createServerClient queryStoreInitialData and toInitialValue that we used above src lib gql client jsimport browser from app environment import urls from config import createClient queryStore from urql svelte import derived readable from svelte store Helper function to create an urql client for a server side only load function param import sveltejs kit Cookies cookies returns export function createServerClient cookies return createClient FIXME adjust your graphql url url urls gql fetch FIXME if you don t need to authenticate delete the following object fetchOptions credentials include headers FIXME if you want to set a cookie adjust the cookie name Cookie gql session cookies get gql session Helper method to send a GraphQL query but use the data from the SvelteKit load function initially param any queryArgs param any initialValue returns export function queryStoreInitialData queryArgs initialValue if initialValue initialValue error amp amp initialValue data throw new Error No initial value from server let query readable fetching true if browser query queryStore queryArgs return derived query value set gt if value fetching set initialValue source server fetching true else set value source client Make the result object of a urql query serialisable template T param Promise lt import urql svelte OperationResult lt T any gt gt import urql svelte OperationResult lt T any gt result returns Promise lt fetching false error undefined name string message string graphQLErrors any networkError Error response any data T undefined gt export async function toInitialValue result const error data await result required to turn class array into array of javascript objects const errorObject error undefined if errorObject console warn error errorObject graphQLErrors error graphQLErrors map e gt e errorObject networkError error networkError errorObject response value response omitted return fetching false error error errorObject data Link to the Gist End remarksEven though I think this solution is not too bad I wish urql svelte would implement a better way to handle SSR with sveltekit I posted a question on the urql GitHub discussions board but I have not gotten any response yet This article was written with svelte kit version next and urql svelte version I will try to update this article as I update my codebase to newer versions If this post helped you or you found a better or different way to solve SSR with urql please let me know in the comments write me an email or tag me on twitter TiimB |
2022-10-15 20:38:33 |
海外科学 |
NYT > Science |
20 Nations at High Risk From Global Warming Might Halt Debt Payments |
https://www.nytimes.com/2022/10/14/climate/climate-disasters-poor-nations-iimf.html
|
climate |
2022-10-15 20:22:23 |
ニュース |
@日本経済新聞 電子版 |
安心して失敗できる社会を ホームレスの「再出発」支援
https://t.co/yvERAmBkjz |
https://twitter.com/nikkei/statuses/1581375299174166528
|
社会 |
2022-10-15 20:03:46 |
ニュース |
@日本経済新聞 電子版 |
時刻表ミュージアムで「時間旅行」を
https://t.co/clmdWpakxY |
https://twitter.com/nikkei/statuses/1581374779273068544
|
時間旅行 |
2022-10-15 20:01:42 |
ニュース |
@日本経済新聞 電子版 |
親が認知症、後見人になったら? 財産管理し家裁に報告
https://t.co/JmlRjOLAiw |
https://twitter.com/nikkei/statuses/1581374778148913152
|
財産 |
2022-10-15 20:01:42 |
ニュース |
@日本経済新聞 電子版 |
鉄道開業150年 私たちは、駅をめざして旅に出る
https://t.co/RkvPwjTwa0 |
https://twitter.com/nikkei/statuses/1581374777042010112
|
開業 |
2022-10-15 20:01:42 |
ニュース |
@日本経済新聞 電子版 |
倍速社会で見失うもの
https://t.co/mfihvpJbwI |
https://twitter.com/nikkei/statuses/1581374776060575744
|
社会 |
2022-10-15 20:01:41 |
ニュース |
@日本経済新聞 電子版 |
京都大学・白眉センター 「ポンコツ」望遠鏡で木星観測
https://t.co/PemvMmjalo |
https://twitter.com/nikkei/statuses/1581374761858650112
|
京都大学 |
2022-10-15 20:01:38 |
ニュース |
@日本経済新聞 電子版 |
教育移住、親子ですくすく 1週間から保育園留学も
https://t.co/G7oxMcRxOI |
https://twitter.com/nikkei/statuses/1581374760868806661
|
週間 |
2022-10-15 20:01:38 |
ニュース |
@日本経済新聞 電子版 |
「億り人」解体新書 荒れ相場に攻め、視線は海外・長期
https://t.co/oevDG2ZRP4 |
https://twitter.com/nikkei/statuses/1581374759904104449
|
解体新書 |
2022-10-15 20:01:37 |
ニュース |
@日本経済新聞 電子版 |
米の欧州向けLNG輸出2.6倍 1~9月、ロシア産減補う
https://t.co/oSJkMnDOvY |
https://twitter.com/nikkei/statuses/1581374758758715392
|
輸出 |
2022-10-15 20:01:37 |
ニュース |
@日本経済新聞 電子版 |
観光地人出回復・円安「断固たる措置」・英の減税撤回
https://t.co/ikzAy4OWGd |
https://twitter.com/nikkei/statuses/1581374757756633089
|
観光地 |
2022-10-15 20:01:37 |
ニュース |
@日本経済新聞 電子版 |
クレディ・スイスに逆風 再建策焦点に
https://t.co/5ERfBzVmW3 |
https://twitter.com/nikkei/statuses/1581374756766371840
|
逆風 |
2022-10-15 20:01:37 |
ニュース |
@日本経済新聞 電子版 |
日産・ルノー、親子から対等へ 「15%出資」協議の行方
https://t.co/sAszpFuI8L |
https://twitter.com/nikkei/statuses/1581374755802091521
|
親子 |
2022-10-15 20:01:36 |
ニュース |
@日本経済新聞 電子版 |
きょう共産党大会開幕 最高指導部「習派」過半も
https://t.co/xS4VpfqKyX |
https://twitter.com/nikkei/statuses/1581374754858364928
|
開幕 |
2022-10-15 20:01:36 |
ニュース |
@日本経済新聞 電子版 |
高所得75歳以上の保険料上げ検討 大企業健保も負担増
https://t.co/BOdq7GIrTF |
https://twitter.com/nikkei/statuses/1581374753906241536
|
検討 |
2022-10-15 20:01:36 |
ニュース |
@日本経済新聞 電子版 |
「越境EC」円安で再脚光 2年で8割増、中小に商機
https://t.co/GIKo5Wki5E |
https://twitter.com/nikkei/statuses/1581374752584650752
|
越境ec |
2022-10-15 20:01:36 |
ニュース |
BBC News - Home |
Evin prison fire: Gun shots and sirens heard at notorious detention centre |
https://www.bbc.co.uk/news/world-asia-63271817?at_medium=RSS&at_campaign=KARANGA
|
political |
2022-10-15 20:15:30 |
ニュース |
BBC News - Home |
Reece James: England and Chelsea defender set to miss World Cup with knee injury |
https://www.bbc.co.uk/sport/football/63273316?at_medium=RSS&at_campaign=KARANGA
|
injury |
2022-10-15 20:17:07 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
税理士試験突破の王道は今や「試験科目免除大学院への進学」、入試難易度リスト大公開! - 会計士・税理士・社労士 経済3士業の豹変 |
https://diamond.jp/articles/-/310960
|
会計学科 |
2022-10-16 05:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
味の素の藤江社長が「売り上げを伸ばす過度な投資はしない」と断言する理由 - 味の素 絶好調下の焦燥 |
https://diamond.jp/articles/-/310980
|
売り上げ |
2022-10-16 05:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
士業の上手な生かし方とNG士業の見抜き方、企業にとって“センセイ”は働かせてナンボ! - 会計士・税理士・社労士 経済3士業の豹変 |
https://diamond.jp/articles/-/310959
|
代表取締役 |
2022-10-16 05:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
英語の雑談を切り上げるとき「絶対言ってはいけない」フレーズとは? - ビジネスを強くする教養 |
https://diamond.jp/articles/-/311152
|
言い回し |
2022-10-16 05:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
稲盛和夫氏の信念「思考は必ず現実になる」、実践した超積極思考の神髄 - 「超一流」の流儀 |
https://diamond.jp/articles/-/311305
|
稲盛和夫 |
2022-10-16 05:05:00 |
ビジネス |
東洋経済オンライン |
結婚相手に「容姿」を求める女性が過去最高の現実 男性は女性に「経済力」を求めるようになった | ソロモンの時代―結婚しない人々の実像― | 東洋経済オンライン |
https://toyokeizai.net/articles/-/625473?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
東洋経済オンライン |
2022-10-16 05:30:00 |
海外TECH |
reddit |
GAM Esports vs. Top Esports / 2022 World Championship - Group C / Post-Match Discussion |
https://www.reddit.com/r/leagueoflegends/comments/y4y9vx/gam_esports_vs_top_esports_2022_world/
|
GAM Esports vs Top Esports World Championship Group C Post Match DiscussionWORLDS Official page Leaguepedia Liquipedia Eventvods com New to LoL GAM Esports Top Esports With this win Rogue are guaranteed a top finish in group C GAM Leaguepedia Liquipedia Website Twitter Facebook YouTube TES Leaguepedia Liquipedia Website Twitter MATCH GAM vs TES Winner GAM Esports in m Game Breakdown Bans Bans G K T D B GAM caitlyn azir maokai akali nidalee k H O H M M M TES aatrox yuumi sejuani amumu nautilus k I B E GAM vs TES Kaiya ornn TOP renekton Wayward Levi karthus JNG graves Tian Kati sett MID ahri knight Stye kalista BOT lucian JackeyLove Bie renata glasc SUP nami Mark This thread was created by the Post Match Team submitted by u Soul Sleepwhale to r leagueoflegends link comments |
2022-10-15 20:49:45 |
海外TECH |
reddit |
my boyfriend (nevermo) and i (exmo) have a 4 hour layover at SLC airport |
https://www.reddit.com/r/exmormon/comments/y4xa2j/my_boyfriend_nevermo_and_i_exmo_have_a_4_hour/
|
my boyfriend nevermo and i exmo have a hour layover at SLC airportentertain us at the airport bar…MORMON BINGO GO submitted by u emergency peanut to r exmormon link comments |
2022-10-15 20:06:00 |
コメント
コメントを投稿