投稿時間:2021-10-12 08:37:54 RSSフィード2021-10-12 08:00 分まとめ(50件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 次期「Apple TV」はデザイン刷新か − 「Nintendo Switch」スタイルのゲーム機も開発中との噂 https://taisy0.com/2021/10/12/147257.html siriremote 2021-10-11 22:27:09
IT 気になる、記になる… iFixit、内部が透けて見えるような壁紙の「iPhone 13/13 mini」版を公開 https://taisy0.com/2021/10/12/147254.html ifixit 2021-10-11 22:02:10
TECH Engadget Japanese ガバッと開き丸洗いOK。マスク表面に触れずに衛生的に保管ができるマスクケース「Xpure Mask Case」 https://japanese.engadget.com/xpure-mask-case-223538467.html 隅々まで消毒可能で衛生的スペアマスクだけじゃないICカードや小物も収納可能▍ガバッと全開マスク表面に触れず素早く出し入れL字型のケースでガバッと広く開くため、菌やウィルスが付着したマスク表面に触れずに、耳紐を持って収納することができます。 2021-10-11 22:35:38
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 半導体不足が日系自動車大手の中国販売直撃 9月はトヨタ、ホンダ、日産軒並みマイナス https://www.itmedia.co.jp/business/articles/2110/12/news075.html itmedia 2021-10-12 07:46:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 【動画】エネルギー価格上昇、平均時給の増加基調などインフレ懸念への警戒感が一層高まる https://www.itmedia.co.jp/business/articles/2110/12/news064.html ITmediaビジネスオンライン【動画】エネルギー価格上昇、平均時給の増加基調などインフレ懸念への警戒感が一層高まる原油先物価格が大きく上昇、サプライチェーンの混乱や人手不足によるコスト増加が企業収益を一段と圧迫するとの思惑が広がりインフレ懸念が高まりました。 2021-10-12 07:40:00
IT ITmedia 総合記事一覧 [ITmedia エンタープライズ] 理想のデータ活用人材を育てたのに、なぜ「データドリブンな組織」になれないのか https://www.itmedia.co.jp/enterprise/articles/2110/12/news006.html itmedia 2021-10-12 07:30:00
IT ITmedia 総合記事一覧 [ITmedia エンタープライズ] Microsoft、マルウェアの隠れみのに利用されるExcel 4.0マクロをデフォルトで無効化する方針を発表 https://www.itmedia.co.jp/enterprise/articles/2110/12/news040.html excel 2021-10-12 07:15:00
IT ITmedia 総合記事一覧 [ITmedia エグゼクティブ] 駅舎を改修したレトロモダンなまちの秘密基地、Sta.神田の魅力とは https://mag.executive.itmedia.co.jp/executive/articles/2110/12/news049.html itmedia 2021-10-12 07:04:00
TECH Techable(テッカブル) Nishikaと特許庁のコンペ! 類似商標画像を高精度で検出する機械学習モデル開発へ https://techable.jp/archives/164239 nishika 2021-10-11 22:00:40
js JavaScriptタグが付けられた新着投稿 - Qiita [javascript] Object.keysの使い方 https://qiita.com/morimoto-shin/items/e43247d411d40fd6b383 javascriptObjectkeysの使い方javascriptObjectkeysの使い方ObjectkeysとはMDNWebDocsにはこのように説明されています。 2021-10-12 07:19:54
js JavaScriptタグが付けられた新着投稿 - Qiita これからReact始めたい人のための今日だけでできるTODO#21 useContext① https://qiita.com/tanimoto-hikari/items/f1799aaa610900b6aa13 これからReact始めたい人のための今日だけでできるTODOuseContext①useContextとはpropsを直接渡したい子孫コンポーネントに値を渡すことができるフックです。 2021-10-12 07:01:33
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) スプレッドシートのグラフの状態を維持し、データ範囲のセルを移動する方法 https://teratail.com/questions/363956?rss=all 複合 2021-10-12 07:22:55
Ruby Rubyタグが付けられた新着投稿 - Qiita RubyでArrayを使う方法 https://qiita.com/nogizakapython/items/1e88934a1037515b3f50 RubyでArrayを使う方法RubyでArrayを使う方法です。 2021-10-12 07:53:31
Ruby Rubyタグが付けられた新着投稿 - Qiita Raccでかんたんな自作言語のパーサを書いた https://qiita.com/sonota88/items/97ba1f0c377fbe86d5b1 Raccでかんたんな自作言語のパーサを書いた簡単に概要を書くと下記のような感じです。 2021-10-12 07:24:30
Git Gitタグが付けられた新着投稿 - Qiita Git よく利用するコマンド https://qiita.com/hiro_rookie/items/9b4ad57eab450d7f0836 2021-10-12 07:11:32
海外TECH Ars Technica Toddler dies of Ebola after 3 suspicious deaths in DRC; 148 contacts identified https://arstechnica.com/?p=1803225 contacts 2021-10-11 22:00:36
海外TECH DEV Community Building a client database of people in React https://dev.to/seven/building-a-client-database-of-people-in-react-55oe Building a client database of people in ReactEver wondered how to get access to a whole lot of information about people on the internet Like any information about anyone In this article we ll be building a client side application with ReactJS on the web that ll integrate Kelvin Data API at the frontend The Kelvin Data is an API platform that allows you to access the profile of people on the web You can search for a specific person either with their email address LinkedIn profile here you ll have to provide the person s LinkedIn URL i e or their phone numbers Now let s see how we can create an app that we ll consume this API with But before you read this article any further you should have a basic knowledge of React Data fetching with Hooks in React Conditional rendering in React String template Literals in JavaScript React components and props The KelvinData dashboard When you signup on to the platform you ll have access to a personalized dashboard that you can use to watch your subscriptions manage your API keys and do a lot more A search playground is also on the dashboard where you can test the features of the API You can decide to search for anyone either with their names email addresses LinkedIn profiles or phone numbers This article is going to cover how you can search for people with their full name alone Getting StartedFor the scope of this article we ll be using NextJS to bootstrap our app This does not mean that the create react app library wouldn t work You can make use of anyone that you find convenient We re using nextjs because of its simplicity You can read more about NextJS hereLet us start by installing the dependencies that we need in this project We d start by creating a nextjs app The command below does that for us npx create next app name of your app We ll make use of the styled components library for styling our app and the axios library to fetch data from the API We wouldn t be covering much of the styling aspect in this article You can find the full app styles here Let s get the dependencies above by typing the command below into our terminal npm install axios styled components react iconsLet us have a look at the file structure of the app below We ll focus on the important files that we need in this app so it ll be concise pages api users js app js index js src components Card js env local Overview of the components in our Next js appIn this section we are going to see the different files that make up the architecture of this project and their respective functions below The pages directory is where all the routing of the app takes place This is an out of the box feature of Nextjs It saves you the stress of hard hard coding your independent routes pages api the api directory enables you to have a backend for your nextjs app inside the same codebase instead of the common way of creating separate repositories for your REST or GraphQL APIs and deploying them on backend hosting platforms like Heroku and so on With the api directory every file is treated as an API endpoint If you look at the api folder you ll notice that we have a file called user js in it That file becomes an endpoint which means an API call can be performed using the path to the file as the base URL const getData async gt axios get api users then response gt response then response gt console log response data catch err gt console log err pages app js is where all our components get attached to the DOM If you take a look at the component structure you ll see that all the components are passed as pageProps to the Component props too It is like the index js file when using Create React App The only difference here is that you are not hooking your app to the DOM node called “root React render document getElementById root lt App gt index js is the default route in the pages folder That is where we ll be doing most of the work on this project When you run the command below it starts up a development server and the contents of index js are rendered on the web page npm run devCard js is the component that holds displays the data we get from the API on the webpage env local is where we re storing the API key that ll enable us to consume this API Writing the server side API call In the previous section we saw the files that we ll be interacting with and their specific functions In this section we would have a look at how we can consume the API The reason why we re writing the API call at the server side is for securing our API key and Nextjs already makes it an easy task for us With the API routes in Nextjs we can perform our API calls without the fear of our API keys being revealed on the client side You may have been wondering what the essence of the environment variable in the env file is in this scenario The environment variable which is our API key can only be available in development mode That is why we can do something like process env api key and get access to the environment variable But the moment you deploy your app to platforms like netlify or vercel the mode changes to production which makes the nodejs process object unavailable on the client side Now that you have seen the reason why need to write a server side API call Let s get to it right away users jsimport axios from axios export default async function users req res const query firstName lastName req const baseUrl lastName lastName amp firstName firstName amp apiKey process env KEY const response await axios get baseUrl res status json data response data In the snippet above we created an asynchronous function called users It takes in two arguments req which stands for “request in full and res which is “response in full The req argument has some properties or “middlewares as the Nextjs docs calls it that can be accessed when we re consuming our API one of them is req query You ll notice that we destructured the query property in the snippet above so we would be able to pass those variables as values to the query properties of the API endpoint Take a look at it below You can read more about the in built middlewares that comes with the req argument here const query firstName lastName req The base URL takes the destructured query properties as values and the apiKey is gotten from the env file via the nodejs process object The destructured query properties are taken as requests that will be sent from the input values of the form component which we ll be creating in the next section to the API once it is received we get a response that corresponds with the request we made const baseUrl lastName lastName amp firstName firstName amp apiKey process env KEY The next process the function has to complete is the response from the asynchronous API call The snippet below assigns the API call which we are perfoming with the axios library to a variable response On the next line the res argument uses the status method which is used to send a JSON response to us then we can assign the response variable as a property of dataYou can read more about the various HTTP status codes hereconst response await axios get baseUrl res status json data response data Building the form componentIn the previous section we saw how we can write our API calls on the server side we ll be using that API call in this section as we create the form component that will send the first and last name values from the input fields to API query parameters We ll be keeping the code snippets short so that this article doesn t get too long Let s start by taking a look at the content of index js below import React from react import styled from styled components import axios from axios import Card from components Card const Wrapper styled section padding px px height width remaining style goes here const UserAPIComponent gt const userData setUserData React useState const firstName setFirstName React useState const lastName setLastName React useState const getuserData async gt api call goes here const handleSubmit e gt e preventDefault getuserData return lt Wrapper gt lt h gt Search for Anyone lt h gt lt form onSubmit handleSubmit gt lt label htmlFor firstname gt First name lt label gt lt input type text name firstname value firstName placeholder First Name onChange e gt setFirstName e target value gt lt label htmlFor lastname gt Lastname lt label gt lt input type text name lastname value lastName placeholder Lastname onChange e gt setLastName e target value gt lt div className btn container gt lt Button gt Search lt Button gt lt div gt lt form gt lt div className results container gt userData lt Card result userData gt loading lt div gt lt Wrapper gt export default UserAPIComponent Since this is a React component that is receiving data from an API endpoint it should have an internal state of its own The snippet below shows how we defined the different state variables with React Hooks const userData setUserData React useState const firstName setFirstName React useState const lastName setLastName React useState The firstName and lastName variables receive the text values that are typed into the input field by anyone The userData state variable helps us store the response that we get from the API call in an array so we can use the JavaScript map method to render the response on the webpage Notice how we re using axios to get data from the API endpoint and how the base URL is not a typical https URL instead it is the path to the file where we made the server side API call before const getuserData async gt axios get api usersfirstName firstName amp lastName lastName headers Accept application json Access Control Allow Origin then response gt response then response gt setUserData response data data catch err gt console log err We repeat almost the same process in the user js file but this time around with the necessary fetch headers and assignment of the state variables to the API query parameters In the second then method we ensured that the response from the API call is treated as an array hence the need for response data data If we had stopped at setUserData response data JavaScript will throw a type error whenever we try to do the following userData map users index gt return some JSX This is because response data is having an object data type and the map operation does not work on JavaScript objects only arrays The handleSubmit handler ensures that the webpage isn t reloaded at every API call upon the click of the search button const handleSubmit e gt e preventDefault getuserData Building the card componentThe card component serves as the presentational component of the app Data gets passed down to it through the usage of props in React Once again for the sake of brevity we ll not be taking a look at all the major content of the card component Let s take a look at the modified structure belowimport React from react import FiUser from react icons fi import styled from styled components const Wrapper styled div height width margin px px background fff box shadow px px px rgba border radius px padding px px const Card result gt return lt gt result map users index gt return lt Wrapper className users card key index gt lt p gt lt span gt lt FiUser gt lt span gt users name full null users name full no name data lt p gt lt p gt Title users employments title lt p gt lt p gt Organization users employments organization name null users employments organization name no employment info lt p gt lt Wrapper gt lt gt export default Card The result prop is passed to the Card component which in turn gets utilized in the App component in index js The ternary operator checks for the validity of userData if it is true the Card component is rendered If it isn t the loading… string is displayed on the webpage lt div className results container gt userData lt Card result userData gt loading lt div gt You ll also notice how we re performing conditional rendering with the ternary operator in the “Organization paragraph below If there isn t any data that corresponds with a user s organization details the no employment info string is displayed If there is the user s organization is displayed lt p gt Organization users employments organization name null users employments organization name no employment info lt p gt ConclusionThe video below shows the end result of what we have been building all along from the beginning of this article You can always check your browser s dev tools move to the network tab to see if the API key is showing or not If you want to have a look at the code base here s the link to it The link points to the specific file of this article in the repository You can check out my other article demos here and also have a look at the repository as a whole If you read this article up till this point thank you for doing so and please don t forget to share it 2021-10-11 22:47:34
海外TECH DEV Community How To Open a Great Pull Request https://dev.to/jeff_codes/how-to-open-a-great-pull-request-5994 How To Open a Great Pull Request Your GoalWhen opening a Pull Request PR your goal is to get your code merged into the main branch so that it can be released amp a part of the code base However before your code can be merged it first must be reviewed The pull request is where this review will take place In order to get your code reviewed amp approved as fast as possible you want to create a great Pull Request This Pull Request should make the code reviewers life as easy as possible If the code reviewer has to leave the pull request to get more information then it is not a good pull request All relevant information should be included in the Pull Request There is nothing worse than a huge number of file changes and an empty PR description form There are a bunch of different Pull Request templates that you can find on the internet that are great but regardless of which template you end up using make sure the following information is included WhatYou want to make sure that you adequately describe the requirements that your change is implementing or fixing Having the code reviewer have to guess what your change is doing is never a good idea If you have a ticket number for your change make sure to link it WhyNow that the reviewer knows what your code is trying to accomplish it is time to give some context as to why you are doing things the way that you are doing them You don t and shouldn t explain every single line of code No reviewer is going to read an entire dissertation about making a page more mobile responsive However it is good to explain things from a high level It is also good to explain why you chose to do things a certain way Try to think of the possible questions that your reviewers might have before they ask it This will save time in the long run If you are referencing any outside material make sure to link it ValidationAs a developer I have trust issues I ve seen release branches get broken too many times So to ease your reviewers doubts make sure to include validation that your code is doing what it is supposed to be doing Validation can be a variety of different things If you are working on a frontend change make sure to include screenshots or videos GitHub now allows you to add videos to your PR Also ensure that your screenshots or videos take into consideration various screen sizes such as mobile and desktop Working on creating a new editing REST endpoint Add a curl and its response to the PR Keep your GIT History CleanSave yourself time amp energy and always ensure that your git history is up to date with the main branch Merge conflicts are the worst and best to be avoided all together However sometimes they cannot be avoided In that case you need to be proactive about resolving them instead of having someone tell you to resolve them This just increases the time that it takes to get your code merged into the main branch You also want to make sure that you are writing good amp descriptive commit messages Fixed the bug amp Should work now aren t gonna cut it This holds especially true if you are not doing a Squash amp Merge and instead creating a merge commit for each commit when merging to the main branch CommunicateYour code is not you I am going to repeat that because it is so important YOUR CODE IS NOT YOU You should not take offense when reviewers request changes You should try and take this as a learning moment be grateful that you are able to learn a new or better way of doing something Communicate openly with reviewers You should answer any question that they may have while providing them with links amp examples to make their life as easy as possible 2021-10-11 22:40:57
海外TECH DEV Community Mocking Back-ends for React Apps with MirageJS https://dev.to/anikcreative/mocking-back-ends-for-react-apps-with-miragejs-jgb Mocking Back ends for React Apps with MirageJS Seven tips to help you avoid bottlenecks and future proof your mock back end️DisclaimerThis article assumes you have some familiarity with the React framework and Javascript and Typescript fundamentals It also assumes you are comfortable with concepts and terms related to relational databases Table Of ContentsWhat led me to consider Mirage Don t put everything in one file Start with a plan Define Typescript interfaces for models Consider a hybrid approach for generating realistic seed data Split up and aggregate route handlers Create API client functions for UI components Set up passthroughs and a unique namespace for mock routesClosing thoughts What led me to consider Mirage I recently helped create a high fidelity React based prototype for a new product still in its early stages We were not entirely certain if the product would solve the problem it was intended to solve for our customers We needed feedback and in order to get that feedback we needed to put something in front of potential customers that wasn t merely a slideshow or clickable mockup something closer to the “real thing We wanted them to be able to explore and interact with the prototype in a much more realistic manner than they otherwise could if it were just a slideshow or mockup with limited interaction targets and a strict pre determined “flow This would ultimately help us decide whether we could continue building out the rest of the application as is or if we needed to go back to the drawing board Building such a prototype without an actual back end would require significantly fewer resources and would therefore pose less of a risk to our organization in terms of cost should the concept prove to be unviable But how does one go about building a UI prototype with realistic data and simulating the ability to interact with and modify said data without an actual back end This is the question that first led me to consider a library like Mirage Mirage and other tools like Mirage allow us to mock back ends and APIs for JavaScript applications With a mock data layer fixed and or dynamically generated mock data and an accompanying API you can build your client application simulate the accessing and modifying of data and even run tests as though the back end and API already exist I don t plan on using this article exclusively to try and convince you to use Mirage on a future project I think the MirageJS documentation already makes a great case as to the “why The documentation also has excellent step by step guides and tutorials so this article is not a “getting started guide either Instead I plan to use this opportunity to share what I feel are some good “best practices drawn from my own experiences Don t put everything in one file To start off it s entirely possible to define and configure the entire mock back end in one massive function inside a server ts file or server js file if you re not using Typescript In fact if you follow Mirage s tutorials that s basically what they ll have you do initially all of the code for the mock back end ーmodels routes and route handlers fixtures seed data factories and everything else ーin one file However I ve found that this approach becomes cumbersome in the long run especially once the mock back end becomes more complex and once you start adding custom route handlers Here is how I like to organize my Mirage code src root directory of React app ├ーcomponents ー┐ ├ーhooks ├ーReact app components and ├ー ー┘other client app code └ーmock api ├ーmodels ├ーfactories ├ーroutes ├ーserializers ├ーclients ├ーserver ts └ーindex tsI ll be going over the individual pieces in more detail shortly but here s a general summary I keep all of the Mirage mock back end code inside a mock api or similarly named directory I keep the main server ts file where my Mirage server instance generator function is defined directly inside this directory The models directory is where I store Typescript interfaces for all data models as well as other interfaces enums and other type declarations related to the data The factories directory contains sample data fixtures for seeding the mock database with initial sample data It also contains any factories responsible for generating seed data with custom generator functions I could have also named this folder data The routes directory contains code that implements custom route handlers and registers routes with the server instance For instance if I defined a custom HTTP GET endpoint that allowed a list of items to be searched sorted and filtered I would place that code inside this directory The serializers directory is for any custom data serializers that I ve defined in case I find it necessary to serialize certain data in a specific way after processing queries The topic of serializers is beyond the scope of this article but the Mirage documentation has plenty of information on the subject The clients directory contains API client functions that simplify the process of sending API requests from the front end and reduce the amount of repeated boilerplate code I have to write when doing so The advantages of splitting out code in this fashion should be fairly self explanatory but two things in particular stand out to me When committing changes to the Mirage code diffs will be far easier to understand and interpret Instead of viewing a hodgepodge of changes within one massive file changes will appear more surgical split out over several files It should be easier to tell what changed and what didn t and easier to spot mistakes Maintenance becomes easier Avoid having to scroll up and down an enormous file to make several related changes or to compare two or more related things It s much easier to locate something by pulling up a separate aptly named file than by hunting for it inside thousands of lines of code Start with a plan For Mirage “models similar to tables in a relational database are the building blocks of the mock back end they define the schema on which everything stands Before getting too far ahead I recommend taking some time to plan out the models and relationships between those models It s very easy to get started with Mirage and I initially made the mistake of running before I could walk I hastily defined the models and relationships thereof and started building the mock back end and the various route handlers I soon discovered that I had overlooked some crucial aspects of the schema and ended up spending hours reworking the models seed data and other related things In the example below I ve defined some models for a hypothetical application s mock back end via the models config property import createServer Model from miragejs export function makeServer const server createServer models product Model order Model orderItem Model tag Model user Model userFavorite Model return server These models are not very useful at the moment As you may suspect just by reading their names there are some relationships between these distinct models Multiple OrderItems for instance comprise and are related to one Order An item marked as a UserFavorite is related to a particular Product and User To see the relationships between these models more clearly let s first create a simple schema This of course is a highly simplified contrived example The benefits of such preparation become more obvious when grappling with complex realistic schemas The Mirage API provides easy ways to define relationships one to many many to one etc between models using the belongsTo and hasMany helpers Let s configure our models to reflect those relationships now that we know what they are export function makeServer const server createServer models product Model extend tag hasMany order Model extend user belongsTo orderItem Model extend order belongsTo product belongsTo tag Model extend product hasMany user Model extend userFavorite hasMany userFavorite Model extend user belongsTo product belongsTo Mirage will automatically assign primary and foreign keys for each model based on how you ve configured the relationships When accessing UserFavorite data in the mock database for instance you ll find that each UserFavorite record now has userId and productId fields that serve as foreign keys that correspond to the primary keys of particular instances of a User and a Product in the database respectively Define Typescript interfaces for models if your project implements Typescript For obvious reasons if your application does not implement Typescript this tip probably won t be very useful in your particular case In the previous example the models we defined will allow us to take advantage of Mirage s object relational mapping ORM capabilities When running queries on the mock database we will serialize the results into JSON and convey them back to the React app simulating exactly what would happen with an actual back end with a web API The JSON result must then be deserialized in the client app before the data can be processed by the React components Assuming the React app implements Typescript wouldn t it be nice if the components had access to interfaces and types that defined the structure of the data Plus if certain components needed to pass around data via props we could use said interfaces to declare prop types The schema we defined earlier will come in handy for this We can now easily declare Typescript interfaces for each of the models in our mock back end Let s start with the Tag and Product models We know there s a many to many both ends optional relationship between products and tags as one tag could be associated with one multiple or zero products and each product could be associated with one tag many tags or no tags at all Actually because we suggested a many to many relationship in the model configuration Mirage will automatically add a property to each Tag in the database that tracks all of the related products associated with that tag But we don t necessarily want an array of Products for each Tag object as far as our client app is concerned The Tag model s corresponding interface is pretty simple As for the Product interface each product object will contain an array of tags Each member in this array is a Tag object Now let s say our hypothetical UI will display products in a list with each individual product shown as a card containing that product s information Let s say that these cards are rendered using some ProductCard component interface ProductCardProps name string seller string price number type string tags string function ProductCard props ProductCardProps return In another part of the UI a list of “recommended products is displayed with minimal information about each product This RecommendedProduct component might be used to display each product snippet interface RecommendedProductProps name string seller string price number function RecommendedProduct props RecommendedProductProps return There could be many more components like these in the app each displaying or processing product data in some form or fashion I ve purposefully omitted their implementation details because right now we re more concerned with their props APIs The props interfaces shown are built to match only the current structure of product data in the mock back end and they feature code duplication What happens if we change the schema so that products no longer had a seller property What if we renamed the price property to cost We would need to remember all of the components that handle product information and then update each of them individually every time such a change occurred We can avoid this by utilizing the Product interface we defined just a while ago We ll have the individual components props interfaces extend that “base type for the product data model import Product from path to mock api code interface ProductCardProps extends Product additional component specific props not present on the base Product model interface RecommendedProductProps extends Pick lt Product name seller price gt additional component specific props not present on the base Product model Now whenever the structure of product data in our mock back end changes we only have to update the Product interface to reflect that change This update will also be reflected in any interface that extends the base Product interface whether entirely or in part For the RecommendedProductProps interface we only care about a select few properties of the Product so we ll use the Pick utility type to extend a subset of the Product interface with just those properties I like to place to these interfaces and other related types in separate files categorized more or less by some “domain to which I believe they belong As shown earlier I usually start with a models directory inside the mock api directory In this models directory I then create sub directories for each distinct domain like so src root directory of React app ├ー └ーmock api ├ーmodels │├ーproducts ││├ーproduct ts ││├ーproduct type ts ││└ーindex ts │├ーorders │├ーorder items │ │└ーindex ts ├ーserver ts └ーindex tsIf you look back at the Product interface we defined a while ago you ll notice it has a property type whose value is a ProductTypeEnum This Typescript enum does not correspond to any model that our mock back end cares about the enum values become integers as far as the mock data or any data transfer objects are concerned But the enum type will still be useful for the React components in the front end Because the two are so closely related in this way I consider both the Product interface and the ProductTypeEnum to be part of the same Product domain The enum is defined inside the product type ts file and the other interface is defined inside product ts I ve purposefully grouped these two files together Consider a “hybrid approach for generating realistic seed data One of the key requirements for my UI prototype was that the sample data needed to be as realistic as possible This involved simulating real customer scenarios acquiring actual addresses and GPS coordinates and so on It s not very common have such an extreme level of detail in a prototype but the experience did force me to figure out creative ways to efficiently generate and handle seed data for a mock back end Mirage allows you to configure initial data for a server instance by defining seed data fixtures using the fixtures config option Because the sheer amount of initial sample data for a realistic prototype could get very large as was the case for my UI prototype I like to keep the sample data fixtures in a separate file and them inject them into the createServer function In the example below when the server instance is first loaded the mock database will be seeded with the following product data product data ts import Product from path to models export const products Product id name Brown Leather Jacket seller Acme Apparel id name Inflatable Pool seller Bravo Recreation id name Small Notepad seller Jones Suppliers Now we just need to pass in the products array to the fixtures config option N B ーremember to use the singular form product when defining models and the plural form products when passing in fixtures import products from path to sample data export function makeServer const server createServer models product Model extend fixtures products return server Fixtures are great if you re willing to write out seed data by hand For obvious reasons this won t be a very good use of your time in more complex scenarios If you need to generate or rows of sample data for instance it s better to find something that can generate the seed data for you instead Luckily Mirage allows you to accomplish this pretty easily using factories Once again I like to keep factories in a separate place and inject them into the server generator function The faker js library comes in really handy for generating all kinds of mock data ーfrom names to phone numbers to addresses and more In the examples below a productFactory is being used to generate Product records as initial seed data for the mock database Custom providers in the productFactory assign product names seller names and other product information using mock data generated by faker modules product factory ts import Factory from miragejs import commerce company from faker export const productFactory Factory extend name string return commerce productName seller string return company companyName price number return Math floor Math random import productFactory from path to sample data export function makeServer const server createServer models factories product productFactory seeds server server createList product return server While this works fine if you need to generate reams of randomized data great for stress testing UI components like tables or lists it still poses a challenge for realistic prototypes By simply letting all of the product names sellers and prices be randomized we may end up with some very strange combinations like cars sold by a “Greenwich Consulting LLC or bananas sold by “Tim s Party Supplies and so on Depending on your context you may or may not care about this level of detail But if you do care you may decide that while some aspects of the seed data can be randomized other aspects ought to remain more tightly controlled Let s say that I wanted some finer control over the names and prices of products but I was okay with randomizing the seller names and other properties of the product Here is a “hybrid approach that will allow me to define just the properties I want direct control over and let the factory handle the rest I start by creating an array of sample data but I only provide values for those properties which I want to control directly I also expose a count of the number of items in the array product data ts import Product from path to models export const products Pick lt Product name price gt name Brown Leather Jacket price name Inflatable Pool price name Small Notepad price export const productCount products length Next I head over to the factory where I keep things the same for properties being randomly generated but change how the other properties are handled When the productFactory iterates over the requested number of items it is asked to generate it will track the specific index of each generated record I can use that index to grab information for the product at that same index in my pre defined list If for whatever reason there isn t anything at that index in my pre defined list this can happen if the factory is asked to generate more records than the number of records in my pre defined list I can have the factory fall back to a randomly generated value instead import commerce company datatype from faker import products from product data export const productFactory Factory extend name index number string return products index id commerce productName seller string return company companyName price index number number return products index price Math floor Math random Lastly we ll go back to the createServer function Instead of generating product records we ll only generate as many as we have data for Remember how we derived productCount from the length of the products array earlier We can now make use of that import productCount productFactory from path to mock data export function makeServer const server createServer models factories product productFactory seeds server server createList product productCount return server The obvious drawback of this hybrid approach is that it can still be painful to generate large sets of mock data since you re having to define at least one or more properties by hand for each record It s best for scenarios where you may want a sizeable set of sample data but you don t necessarily need thousands of rows of said data I like to organize sample data fixtures and factories together in a manner similar to how I organize interfaces for data models src root directory of React app ├ー └ーmock api ├ーfactories │├ーproducts ││├ーproduct data ts ││├ーproduct factory ts ││└ーindex ts │├ーorders │├ーorder items │ │└ーindex ts ├ーserver ts └ーindex ts Split up and aggregate route handlers Similar to the models seed data fixtures and factories I like to keep custom route handlers in separate files and inject them into the server instance generator function src root directory of React app ├ー └ーmock api ├ーroutes │├ーuser favorites ││├ーget favorites by user ts ││├ーadd favorite product ts ││├ーremove favorite product ts ││└ーindex ts │├ーorders │├ーorder items │ │└ーindex ts ├ーserver ts └ーindex tsEach custom route handler gets its own separate file For instance I ve defined a custom route handler that allows a user to designate a product as one of their favorites The implementation of this route handler is in the add favorite product ts file The manner of organization here may invite some questions do route handlers for adding removing a product to a user s favorites belong in the “products domain or in the “user favorites domain The current organization seems to suggest the latter In this hypothetical scenario when designating products as a user favorite we d most likely call a PUT endpoint at the route api user favorites some product id When removing a product from the user favorite list we would call a DELETE endpoint at the same route As this topic is beyond the scope of this article I won t venture too far into the weeds here Certain custom route handlers e g a POST or PUT endpoint that modifies a user s account info may require specific request payloads I like to define Typescript interfaces for all data transfer objects whether they are the request payloads provided to route handlers or the response objects returned I typically keep these interfaces alongside the route handlers to which they are related These interfaces can be exposed to client app components that call the related API endpoints greatly increasing reliability with stricter type controls To ensure that my custom route handlers will get called when API calls are made I must first ensure the routes are being registered with the server instance Let s take a look inside the index ts file in the user favorites directory routes user favorites index ts import Server from miragejs import getFavoritesByUser from get favorites by user import addFavoriteProduct from add favorite product import removeFavoriteProduct from remove favorite product export function registerUserFavoritesRoutes context Server return context get user favorites user userId getFavoritesByUser timing context post user favorites productId getFavoritesByUser context delete user favorites productId getFavoritesByUser I register each individual route handler with the server context which is passed in as the lone parameter of the function All that s left to do is to give this function to createServer so that the server registers these routes upon instantiation We ll need to pass a value for the context parameter To do this we simply pass in a reference to the server instance ーthis import registerUserFavoritesRoutes from routes export function makeServer const server createServer models factories seeds routes registerUserFavoritesRoutes this return server Create API client functions for UI components I like to decouple the mock back end from the client app as much as possible to keep the front end lean and efficient I define API “client functions that serve as convenience wrappers around the actual fetch or axios or whatever call like the addUserFavorite function shown below These functions provide simple APIs for components to use All of the functionality for actually making the API call and returning the results is contained within the functions themselves async function addUserFavorite userId string productId string Promise lt UserFavoriteDTO gt try const response await fetch mock api user favorites productId method PUT cache no cache headers Content Type application json body JSON stringify userId if response ok return response json as Promise lt UserFavoriteDTO gt throw new Error catch reason Handle other errors I aggregate all the client functions for a particular domain inside a single object and then expose this object to the front end const userFavoritesClient list getUserFavorites add addUserFavorite remove removeUserFavorite export default userFavoritesClient Let s say that users can add products to their list of favorites by clicking some button next to a product s information card The component responsible for that interaction needs to be able to call the API endpoint to designate a new “favorite product All we have to do now is call the function we just defined Any information necessary to perform the request information which could determine the actual route or which could comprise a request payload can be passed in as parameter s import userFavoritesClient from mock api function SomeComponent props SomeComponentProps const productId props const userId useContext async function addFavorite try await userFavoritesClient add userId productId catch reason return lt Button onClick addFavorite gt Add to Favorites lt Button gt The component doesn t need to concern itself with which specific route needs to be called or what API base URL ought to be used The developer doesn t have to worry about writing tedious fetch calls every time properly serializing request payloads or deserializing responses The code is clean and streamlined My way of organizing the client functions is pretty rudimentary I put all API client functions related to a particular domain in one file and expose one “client object from each file as shown earlier I place all of these files in one clients directory src root directory of React app ├ー └ーmock api ├ーclients │├ーproducts client ts │├ーorders client ts │├ーuser favorites client ts │ │└ーindex ts ├ーserver ts └ーindex ts Set up passthroughs and a unique namespace for mock routes There are several reasons why you may want to have a mock back end coexist with an actual back end even if temporarily and under specific circumstances During development you may want to have live data flowing into some parts of an application while other parts especially those still under construction remain connected to a mock back end with sample data You might be concerned with mocking up only a portion of the back end that doesn t exist yet while the remainder of the application remains wired up We did eventually start building out the actual back end The sample data when the application was still a UI prototype was of very high quality and greatly facilitated demos and discussions with customers We found that setting up the same amount of realistic data in the actual back end would take days maybe weeks For this and various other reasons we decided to keep a “demo mode for the application When the demo mode was disabled the application would display live data The application s API calls would hit the actual backend and queries would be performed on the actual database Enabling the demo mode would result in the sample data being displayed API calls would be intercepted by Mirage and the mock database instance would instead be the target for all queries performed By default Mirage intercepts all outgoing HTTP requests in a manner similar to monkey patching disallowing communication with web APIs at the same time To allow some requests to pass through you must explicitly declare passthrough routes This is done in the routes config property which we used earlier to inject custom route handlers I tend to put this all the way towards the end import injectUserFavoritesRoutes from routes export function makeServer const server createServer models factories seeds routes this passthrough request gt Custom comparator function Return true if Mirage should allow the request to pass through or false if it should be intercepted return request url includes api v return server In the above example Mirage will not intercept any HTTP requests that include api v as part of the request URL You can also pass in fully qualified domain names if any API requests will go to some external domain and you can provide as many passthrough route declarations as you want const server createServer routes this passthrough https localhost api this passthrough this passthrough I also like to include one additional thing ーa custom namespace for the mock API routes const server createServer routes this namespace mock api this passthrough In the front end calls to the mock back end will now include mock api as part of the route to distinguish them from calls to the actual back end which we will allow to pass through Closing thoughts The recommendations herein likely reflect some of my personal biases They are not meant to be rules or exhaustive guidelines by any means There s so much more to Mirage I ve only scratched the proverbial surface but I ve learned quite a few things along the way I share these tips in the hopes that whether you re new to Mirage or already quite familiar with it they might come in handy for you as well There are even more tips and useful methodologies I d love to share with you but I fear this article would become far too long if I tried to cram them all in here I have plans for an npm package with some useful functions and hooks I ve built that make the process of generating realistic mock data less of a hassle I ll have more details on that in the near future Is there anything in here you particularly liked Do you have concerns or suggestions for improvement or have you spotted any errata Have you worked with Mirage before and have some ideas or approaches you ve found useful which were not mentioned here Please leave a comment Thanks for reading 2021-10-11 22:00:51
海外科学 NYT > Science More Than 30 Countries Join U.S. Pledge to Slash Methane Emissions https://www.nytimes.com/2021/10/11/climate/methane-global-climate.html More Than Countries Join U S Pledge to Slash Methane EmissionsMethane is the second largest driver of global warming after carbon dioxide emissions Scientists say the promised cuts could help avert the worst consequences of climate change 2021-10-11 22:20:29
金融 金融総合:経済レポート一覧 逆転の研究、株価反落の危機感~岸田首相の建て直しに期待:Economic Trends http://www3.keizaireport.com/report.php/RID/471114/?rss economictrends 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 急ブレーキを踏むほど弱くなかった雇用統計~11月テーパリング開始決定へ:Market Flash http://www3.keizaireport.com/report.php/RID/471116/?rss marketflash 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 FX Daily(10月8日)~ドル円、112円台前半まで上昇 http://www3.keizaireport.com/report.php/RID/471119/?rss fxdaily 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 Stablecoinの満たすべき国際標準~BIS(CPMI)の提案内容:井上哲也のReview on Central Banking http://www3.keizaireport.com/report.php/RID/471121/?rss biscpmi 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 米国オプション取引所の現状と歴史:証研レポート http://www3.keizaireport.com/report.php/RID/471125/?rss 日本証券経済研究所 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 ロビンフッド証券のIPO書類から見る収益状況:証研レポート http://www3.keizaireport.com/report.php/RID/471126/?rss 日本証券経済研究所 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 東京における店頭売買承認銘柄~昭和20~30年代の非上場株式市場:証研レポート http://www3.keizaireport.com/report.php/RID/471127/?rss 日本証券経済研究所 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 発足が間近に迫る金融サービス仲介業:証研レポート http://www3.keizaireport.com/report.php/RID/471128/?rss 日本証券経済研究所 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 みずほ経済・金融ウィークリー 2021年10月11日号~先週の内外経済・金融市場動向・評価&今週の注目点 http://www3.keizaireport.com/report.php/RID/471146/?rss 金融市場 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 アジア主要通貨・株価の動き(10月8日まで) http://www3.keizaireport.com/report.php/RID/471149/?rss 国際金融情報センター 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 2021年株式総会シーズンの総括とシュローダーの議決権行使結果:フォーカス http://www3.keizaireport.com/report.php/RID/471166/?rss 議決権行使 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 市場のテーマはインフレに / ユーロ:慎重なコロナ対策が足枷に / 英ポンド:年内利上げ観測は「行き過ぎ」の可能性:Weekly FX Market Focus http://www3.keizaireport.com/report.php/RID/471167/?rss weeklyfxmarketfocus 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 中国恒大集団ショックと不動産バブルをどうみるか:Economic Data Watch http://www3.keizaireport.com/report.php/RID/471168/?rss economicdatawatch 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 投資環境ウィークリー 2021年10月11日号【日本、米国、欧州、オーストラリア】景気減速・物価高への問題意識が、政策当局の現実路線回帰を促すか注目 http://www3.keizaireport.com/report.php/RID/471169/?rss 三菱ufj 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 特別レポート:日米株式 政策当局が景気支援の姿勢強めるまで我慢の展開か http://www3.keizaireport.com/report.php/RID/471170/?rss 三菱ufj 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 【石黒英之のMarket Navi】目線を変えれば別世界が広がる日本株~TOPIXは指数別でEPSに格差 http://www3.keizaireport.com/report.php/RID/471171/?rss marketnavi 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 マーケットフォーカス(米ドル建債券市場)2021年10月号 ~米国国債の利回りが上昇。その他の資産も利回りが上昇... http://www3.keizaireport.com/report.php/RID/471173/?rss 三井住友トラスト 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 ウィークリーレポート 2021年10月11日号~米国株式は反発。石油株や金融株が堅調... http://www3.keizaireport.com/report.php/RID/471175/?rss 三井住友トラスト 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 アジアリート市場動向と見通し(2021年10月号):REITレポート http://www3.keizaireport.com/report.php/RID/471177/?rss 見通し 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 週間市場レポート(2021年10月4日~10月8日)~日本の株式・債券市場、米国の株式市場、外国為替市場 http://www3.keizaireport.com/report.php/RID/471178/?rss 債券市場 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 【注目検索キーワード】脱炭素技術 http://search.keizaireport.com/search.php/-/keyword=脱炭素技術/?rss 検索キーワード 2021-10-12 00:00:00
金融 金融総合:経済レポート一覧 【お薦め書籍】実践スタートアップ・ファイナンス 資本政策の感想戦 https://www.amazon.co.jp/exec/obidos/ASIN/4296000330/keizaireport-22/ gunosy 2021-10-12 00:00:00
金融 ニュース - 保険市場TIMES あいおいニッセイ同和損保とニアミー、ニアミーのアプリ経由で国内旅行保険を提供 https://www.hokende.com/news/blog/entry/2021/10/12/080000 あいおいニッセイ同和損保とニアミー、ニアミーのアプリ経由で国内旅行保険を提供スマートシャトルの手配と同時に保険に加入できるあいおいニッセイ同和損害保険株式会社以下、あいおいニッセイ同和損保と株式会社NearMe以下、ニアミーは年月日、ニアミーのMaaSアプリ経由で加入可能な国内旅行保険の提供を開始した。 2021-10-12 08:00:00
ニュース BBC News - Home Black scientists say UK research is institutionally racist https://www.bbc.co.uk/news/science-environment-58795079?at_medium=RSS&at_campaign=KARANGA black 2021-10-11 22:16:11
ニュース BBC News - Home England boss Southgate 'commits crime' every time he picks team https://www.bbc.co.uk/sport/football/58798060?at_medium=RSS&at_campaign=KARANGA England boss Southgate x commits crime x every time he picks teamEngland boss Gareth Southgate says he commits a crime every time he picks a team because of the players he has to leave out and will make changes for Tuesday s match with Hungary 2021-10-11 22:29:11
LifeHuck ライフハッカー[日本版] かわいい力持ち! 三毛猫のバッグハンガー「nyanger mike」を試してみた https://www.lifehacker.jp/2021/10/243129-machi-ya-nyangermike-review.html nyanger 2021-10-12 08:00:00
サブカルネタ ラーブロ 麺や 四つ葉。。 http://feedproxy.google.com/~r/rablo/~3/mCzCz75BO7g/single_feed.php 夜の訪問者 2021-10-11 23:01:01
北海道 北海道新聞 大リーグ、ブレーブス2勝1敗に Rソックスとレイズが対戦 https://www.hokkaido-np.co.jp/article/599001/ 大リーグ 2021-10-12 07:09:00
北海道 北海道新聞 道内市町村別の週間感染者数(9月26日~10月2日) https://www.hokkaido-np.co.jp/article/598944/ 新型コロナウイルス 2021-10-12 07:05:19
ビジネス 東洋経済オンライン 「学び直しに失敗した父親」にその後何が起きたか 自分には不必要だと思っていると痛い目にあう | リーダーシップ・教養・資格・スキル | 東洋経済オンライン https://toyokeizai.net/articles/-/461266?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2021-10-12 08:00:00

コメント

このブログの人気の投稿

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

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

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