TECH |
Engadget Japanese |
無課金でエンドレスにガチャを回す『もはやガチャだけでいい。』:発掘!スマホゲーム |
https://japanese.engadget.com/gatya-mohaya-211038412.html
|
話題 |
2022-03-13 21:10:38 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] Instagram、ライブ配信でのモデレーター指名が可能に |
https://www.itmedia.co.jp/news/articles/2203/14/news069.html
|
facebook |
2022-03-14 06:38:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia ビジネスオンライン] 感染対策に1.7億円! コロプラが目指した『出社したくなるオフィス』の全貌 |
https://www.itmedia.co.jp/business/articles/2203/14/news033.html
|
itmedia |
2022-03-14 06:15:00 |
Google |
カグア!Google Analytics 活用塾:事例や使い方 |
これだけある!広義のメタバースのプラットフォームまとめ~投資先を間違えるな |
https://www.kagua.biz/social/metaverse/20220314a1.html
|
仮想空間 |
2022-03-13 21:00:56 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
[Python]enumを使って多次元配列をするときの注意点 |
https://qiita.com/satsukiya/items/49aa5faaf3f5f4df6d56
|
WHYてことで、各要素と各行のオブジェクトIDを出力してみます。 |
2022-03-14 06:57:11 |
海外TECH |
DEV Community |
Building a Serverless Application with Next.js and CockroachDB! |
https://dev.to/harshhhdev/building-a-serverless-application-with-nextjs-and-cockroachdb-3pm5
|
Building a Serverless Application with Next js and CockroachDB Hey there Hope you re having a wonderful day or night today we ll be building a simple Next js serverless application deployed on Vercel which uses CockroachDB for the backend serverless database Live app musiclovers vercel appRepository gitlab cockroach serverless with next jsNow before we start I d like to answer the main question out of all databases in the world why are we using one named after a pest Well let me break it down for you here s a list of things which separate CockroachDB from other serverless databases and what caused me to fall in love with it Compatible with PostgreSQL ecosystem CockroachDB uses Postgres compatible SQL meaning that for many developers like me we can use tools directly from the PostgreSQL ecosystem and migrating isn t a pain You re not wasting a penny CockroachDB s pricing is simple and to the point You get GB storage for free which is plenty along with for every extra gigabyte of storage you use Along with this you get M request units monthly and pay just for every M extra request units If this isn t a steal I don t know what is Avoid downtime Behind the scenes your data is replicated at least times meaning that you won t face downtime for things like availability zone outages database upgrades and security patches Even schema changes are online and as a side note no this isn t sponsored by CockroachDB although I will not turn down any sponsorships IntroductionNow that you know why I love CockroachDB let s get into building our actual app Here s what we ll be making A simple clean and dark web app deployed to Vercel where people can share music they like Getting StartedLet s kickstart our Next js and TypeScript project npx create next app latest ts oryarn create next app typescriptLet s start the server now cd music loversyarn devYour server should be running on localhostLet s now begin to write our Prisma data schema and connect it with CockroachDB Start by installing prisma and prisma client Installs both as as development dependenciesyarn add prisma prisma client DNow let s create a new file at prisma schema prisma and open it up Inside here let s configure our datasource and client generator client provider prisma client js previewFeatures cockroachdb datasource db provider cockroachdb url env DATABASE URL Since CockroachDB is just a preview feature as of now we ll have to put it under preview features Check the Prisma list of supported databases if you re reading this post after a while just to double check if it s still in preview Right now Prisma DOES NOT support migrating your schema into CockroachDB for that reason we ll have to write it ourselves in old fashioned SQL and import that into our schema instead Now let s get to work on our schema Since app this will be simple we ll only have a single schema called post For this create a SQL file at root called dbinit sql CREATE TABLE post id SERIAL PRIMARY KEY NOT NULL title VARCHAR NOT NULL content TEXT NOT NULL link VARCHAR NOT NULL createdAt TIMESTAMP NOT NULL DEFAULT CURRENT TIMESTAMP Now let s create a CockroachDB database Sign in and hit create cluster on the clusters dashboard Choose the serverless plan with the region and provider of your choice and name your cluster Inside your cluster we ll start by creating a SQL user Hit add user name your user and generate the password Store the password somewhere safe as you ll need it later on At top hit connect Choose your operating system I m an Arch Linux user so I ll go ahead with Linux Follow the instructions on the modal download the CRDB and run the command inputting in your password in the field which it asks Now head into your terminal and run this to generatecockroach sql url lt connection string gt file dbinit sqlAmazing It should ve worked to create the table inside of CockroachDB Now let s pull your schema from there into your schema prisma file To do this simply run yarn prisma db pull and ta da you should see your schema generated in your file model post id BigInt id map primary default autoincrement title String db VarChar content String link String db VarChar createdat DateTime default now Now that we have that generated let s run yarn prisma generate to generate the Prisma Client Now we have one final step before we can start using Prisma inside of our Next js application Create a new file lib prisma ts Inside of this we ll include a global way of accessing Prisma throughout our application import PrismaClient from prisma client declare global var prisma PrismaClient undefined const prisma global prisma new PrismaClient if process env NODE ENV production global prisma prismaexport default prismaCool Now that we have our database setup it s time to switch gears for a bit and add our custom global styles into this thing Open styles globals css and customise the styling to your needs Here s what I ve got root bg main fff padding margin box sizing border box body padding margin font family Fira Code monospace overflow x hidden color var main background color var bg a color inherit text decoration none selection background var main color var bg webkit scrollbar width px webkit scrollbar track background transparent webkit scrollbar thumb background var main Since we re using a custom font we need to create a new file under pages called document tsx where we import the font import Document Html Head Main NextScript from next document class Doc extends Document render return lt Html gt lt Head gt lt link href Code amp display swap rel stylesheet gt lt Head gt lt body gt lt Main gt lt NextScript gt lt body gt lt Html gt export default DocLet s switch gears from styling and go into our index tsx to edit some things We ll remove the basic content along with removing the imports up top for next image and next head import type NextPage from next import styles from styles Home module css const Home NextPage gt return lt div className styles container gt lt div gt export default HomeLet s now create a new file under our components directory called Posts tsx and import React our styles and Prisma import FC from react import styles from styles Home module css import post as PostType from prisma client Inside of here let s setup our component const Posts FC lt posts PostType gt posts gt return lt gt posts map post i gt lt div className styles post key i gt lt a href post post id className styles title gt post title lt a gt lt p className styles content gt post content length gt post content substring post content lt p gt lt a href post link target blank rel noreferrer className styles link gt post link lt a gt lt div gt lt gt This basically takes in an array of posts as props and maps them out Let s also add in some CSS to spice up this thing post color var main border solid px width inherit padding px px post hover border px solid ccc post focus border px solid var main title font size px font weight text decoration none content margin px title hover text decoration underline link hover text decoration underline Awesome Now let s go back into our index tsx file and strap all of this together Import lib prisma into this file and run prisma findMany inside getServerSideProps to return all posts to display on the screen export const getServerSideProps GetServerSideProps async context gt const posts await prisma post findMany return props posts Now add in the posts component here passing the props which we got from our getServerSideProps function import Nav from components Nav import post as PostType from prisma client const Home NextPage lt posts PostType gt posts gt return lt Post posts posts gt Beware You might run into a JSON serialising problem To fix this simply install the following packages yarn add superjson babel plugin superjson nextNow create a new file babelrc and configure it for superjson presets next babel plugins superjson next Cool We don t have anything displayed yet as our database tables are empty but in the meantime we can style our page to make it look awesome Let s create a Navbar component Create a new file at components navbar Let s import React along with our styles and create a simple navigation bar import FC from react import styles from styles Home module css const Nav FC gt return lt nav className styles nav gt lt Link href gt lt h gt Share Music lt h gt lt Link gt lt Link href new gt lt a className styles create gt New Post lt a gt lt Link gt lt nav gt export default NavLooking good Let s add the navbar styles into our Home module css file nav display flex justify content space between align items center width inherit margin bottom px create padding px color var main border solid px var main transition s linear create hover background color var main color var bg Looking good Now let s import this into our main file Our home component should now include two parent divs and our other components const Home NextPage lt posts PostType gt posts gt return lt div className styles container gt lt div className styles box gt lt Nav gt lt Post posts posts gt lt div gt lt div gt Let s go back to our Home module css file and add in the styles for the parent components container display flex flex direction column justify content center align items center width vw box display flex flex direction column justify content center align items center width vw min width px margin top px Alright that s enough styling for now Let s create a new file under pages called new tsx Let s create a new Form component inside our components directory which includes the form for creating a new post import FC from react import styles from styles New module css const Form FC gt return lt form className styles form gt lt input placeholder Post title className styles input type text gt lt input placeholder Song link className styles input type url gt lt textarea placeholder Why you love this song className styles content gt lt textarea gt lt button className styles create type submit gt Publish Post lt button gt lt form gt export default FormCool Since this is a new page we ll create a new file named New module css under the styles directory This file will focus on styling the form components form display flex flex direction column justify content center align items center width inherit input width inherit padding px background color var bg outline none border px solid font size px font family Fira Code monospace color var main margin px padding px transition s linear input hover content hover border px solid ccc input focus content focus border px solid var main content width inherit font size px font family Fira Code monospace color var main background color var bg outline none border px solid padding px margin px resize none height px create padding px font family Fira Code monospace font size px outline none color var main background var bg border solid px var main transition s linear create hover background color var main color var bg cursor pointer Now once we have that done let s bring it all together in our new tsx file import type NextPage from next import styles from styles Home module css fimport Nav from components Nav import Form from components Form const New NextPage gt return lt div className styles container gt lt div className styles box gt lt Nav gt lt Form gt lt div gt lt div gt export default NewWhew Now that that s over let s work on making our form functional For this we ll create a file called new ts under the pages api directory Inside here let s import Prisma and the required types from Next js import type NextApiRequest NextApiResponse from next import prisma from lib prisma Now inside our function we ll get title content and link from the request s body We ll then wrap our prisma create function in a trycatch block returning a status of with the appropriate JSON fields if it succeeds or a status of and our error if it doesn t We ll also cut off the last digit of the post id as it returns a BigInt const newTrack async req NextApiRequest res NextApiResponse gt const title content link req body try const post await prisma post create data title title content content link link const slug post id toString substring post id toString length return res status json success true slug slug catch err return res status json error err export default newTrackNow to make all this work let s go back to our components Form tsx file and create three new refs inside our Form function for getting different input fields const titleRef useRef lt HTMLInputElement gt null const linkRef useRef lt HTMLInputElement gt null const contentRef useRef lt HTMLTextAreaElement gt null Assign the refs to the appropriate elements inside of the component Let s create a function called createPost in which we use fetch to POST data to our API const createPost e FormEvent lt HTMLFormElement gt gt e preventDefault const headers new Headers headers append Content Type application json const raw JSON stringify title titleRef current value link linkRef current value content contentRef current value const requestOptions RequestInit method POST headers headers body raw fetch api new requestOptions then response gt response json then result gt console log result catch error gt console log error error To purify the content inside of our input fields let s use dompurify const raw JSON stringify title dompurify sanitize titleRef current value link dompurify sanitize linkRef current value content dompurify sanitize contentRef current value Let s also import next router and setup the useRouter hook to redirect after the user creates a post const router useRouter const createPost e FormEvent lt HTMLFormElement gt gt fetch api new requestOptions then response gt response json then result gt router push post result slug catch error gt console log error error Now in our form element we should add in an onSubmit function where we call this method lt form className styles form onSubmit e gt createPost e gt Let s try to create a new post now Fill in all the fields and hit Publish Post when you re done It ll redirect you to another page and send a error as we haven t built out the page yet However if we check our home page we should be able to see the post is created indeed Give yourself a pat on the back if you ve made it this far So what re we waiting for Let s move onto the final step of this project which is creating the View page Let s pass in the post as props and build our component according to the contents of the post import FC from react import styles from styles View module css import post as PostType from prisma client const View FC lt post PostType gt post gt return lt div className styles post gt lt h gt post title lt h gt lt div className styles info gt lt a href post link target blank rel noreferrer className styles link gt post link lt a gt lt p gt Written on post createdAt toLocaleDateString lt p gt lt div gt lt p gt post content lt p gt lt div gt export default View and let s add in our CSS wonderful styles post display flex flex direction column justify content center info display flex justify content space between margin px link hover text decoration underline Brilliant Now let s head back to our pages directory and create a new file at post id tsx Inside here create the PostView component where our Nav and View components come together to form the page Pass in post as a prop for this top level component as we ll be retrieving that from getServerSideProps import styles from styles Home module css import Nav from components Nav import View from components View import post as PostType from prisma client const PostView NextPage lt post PostType gt post gt return lt div className styles container gt lt div className styles box gt lt Nav gt lt View post post gt lt div gt lt div gt Let s move onto getting the post from our database inside getServerSideProps now We ll use the BigInt constructor to turn our params into the BigInt type using that to fetch a unique post export const getServerSideProps GetServerSideProps async context gt const post await prisma post findUnique where id BigInt context params id toString return props post Magnificent Let s try opening up localhost post it should display the content of our post If we try to create a new post now it should display the contents of that too and we re finished WHOO HOO If you made it down here good work I d love to hear your thoughts in the comments below Important links Live app musiclovers vercel appRepository gitlab cockroach serverless with next jsThis post took me a long time to write and create If you enjoyed it please be sure to give it a and follow me for similar posts With that being said I ll conclude this by saying that serverless computing is amazing and has a lot of potential I m planning to write another post sometime soon on when you should or shouldn t use a serverless database so stay tuned and follow for more Enjoy your day goodbye |
2022-03-13 21:47:39 |
海外TECH |
DEV Community |
2022 Tutorial on Creating a Markdown Blog with NextJS |
https://dev.to/alexmercedcoder/2022-tutorial-on-creating-a-markdown-blog-with-nextjs-3dlm
|
Tutorial on Creating a Markdown Blog with NextJS Why Do you want a markdown blogMarkdown makes it much easier to express formatting and focus on writingUpdating your blog means committing to github yay for your heat mapMore practice with markdown which is good writing documentation Since markdown blogs are typically statically rendered they are fast and great for SEOIn this tutorial I will be making a markdown blog with NextJS I do have a tool called create markdown blog which can help spin you up blog template using slightly older versions of Next Nuxt Gatsby Sapper and so forth if you don t want to assemble it from scratch Also AstroJS has a markdown blog template you can easily generate with the command npm init astro Making the BlogGenerate a new nextJS app npm init next app latestcd into the new foldercreate a folder called componentscreate a Header and Footer component components Header jsfunction Header props return lt h gt Header Component lt h gt export default Header components Footer jsfunction Footer props return lt h gt Footer Component lt h gt export default Footercreate a Layout component components Layout jsimport Link from next link import Header from Header import Footer from Footer export default function Layout children return lt div gt lt Header gt children lt Footer gt lt div gt Add the layout component so it shows up on every page pages app jsimport styles globals css import Layout from components Layout function MyApp Component pageProps return lt Layout gt lt Component pageProps gt lt Layout gt export default MyApp create a folder called posts Markdown FilesIn this posts folder is where you ll add markdown files make a file called example post md with the following title This is an example post author Alex Merced category example date bannerImage url to image png tags example This is an example blog postThis is sample content The section above is called Frontmatter where we can add post metadata like title and author You can add as little or as many properties in the frontmatter using YAML syntax Creating the Blog ListWe will create a page blog that will act as where all our blog posts will be listed so created pages blog js with the following Also make sure to install grey matter so can get the Frontmatter the YAML above each blog post npm install gray matter pages blog jsimport fs from fs import matter from gray matter import Image from next image import Link from next link The Blog Page Contentexport default function Blog posts return lt main gt posts map post gt extract slug and frontmatter const slug frontmatter post extract frontmatter properties const title author category date bannerImage tags frontmatter JSX for individual blog listing return lt article key title gt lt Link href posts slug gt lt h gt title lt h gt lt Link gt lt h gt author lt h gt lt h gt date lt h gt lt article gt lt main gt Generating the Static Props for the Blog Pageexport async function getStaticProps get list of files from the posts folder const files fs readdirSync posts get frontmatter amp slug from each post const posts files map fileName gt const slug fileName replace md const readFile fs readFileSync posts fileName utf const data frontmatter matter readFile return slug frontmatter Return the pages static props return props posts Making the Individual Post pagesWe ll need to make a dynamic route that will create a page for every post we have We start by creating pages posts slug js the denotes the dynamic route to nextjs The conents of this page should be the following Also make sure to install markdown itnpm install markdown it pages posts slug jsimport fs from fs import matter from gray matter import md from markdown it The page for each postexport default function Post frontmatter content const title author category date bannerImage tags frontmatter return lt main gt lt img src bannerImage gt lt h gt title lt h gt lt h gt author date lt h gt lt h gt category tags join lt h gt lt div dangerouslySetInnerHTML html md render content gt lt main gt Generating the paths for each postexport async function getStaticPaths Get list of all files from our posts directory const files fs readdirSync posts Generate a path for each one const paths files map fileName gt params slug fileName replace md return list of paths return paths fallback false Generate the static props for the pageexport async function getStaticProps params slug const fileName fs readFileSync posts slug md utf const data frontmatter content matter fileName return props frontmatter content That s it the blog functionality should be working Now you just need to style it tweak it to your liking and write more posts Since this is a NextJS project deployment will be as simple as connecting a github repo to Vercel how awesome is that |
2022-03-13 21:39:40 |
海外TECH |
CodeProject Latest Articles |
Using GFX in PlatformIO |
https://www.codeproject.com/Articles/5327404/Using-GFX-in-PlatformIO
|
platformio |
2022-03-13 21:40:00 |
ニュース |
BBC News - Home |
Brent Renaud: US journalist and filmmaker killed in Ukraine |
https://www.bbc.co.uk/news/world-europe-60729276?at_medium=RSS&at_campaign=KARANGA
|
ukraine |
2022-03-13 21:44:33 |
ニュース |
BBC News - Home |
Bafta Film Awards: Benedict Cumberbatch's The Power of the Dog wins top prize |
https://www.bbc.co.uk/news/entertainment-arts-60675263?at_medium=RSS&at_campaign=KARANGA
|
ukraine |
2022-03-13 21:04:30 |
ニュース |
BBC News - Home |
Garth Crooks' Team of the Week: Ronaldo, Diaz, Eriksen, Yarmolenko, Rudiger |
https://www.bbc.co.uk/sport/football/60730914?at_medium=RSS&at_campaign=KARANGA
|
Garth Crooks x Team of the Week Ronaldo Diaz Eriksen Yarmolenko RudigerWho got Garth into trouble at the petrol station Which striker might be a good buy for Arsenal Find out in Garth Crooks latest Team of the Week |
2022-03-13 21:37:16 |
北海道 |
北海道新聞 |
ロシア、反戦デモで800人拘束 37都市、人権団体が発表 |
https://www.hokkaido-np.co.jp/article/656444/
|
人権団体 |
2022-03-14 06:12:45 |
北海道 |
北海道新聞 |
「ドライブ」に非英語映画賞 英アカデミー、米でも候補 |
https://www.hokkaido-np.co.jp/article/656443/
|
英国アカデミー賞 |
2022-03-14 06:12:45 |
北海道 |
北海道新聞 |
中村敬斗、2ゴールで大勝貢献 オーストリア1部、チロル戦 |
https://www.hokkaido-np.co.jp/article/656449/
|
中村敬斗 |
2022-03-14 06:02:00 |
北海道 |
北海道新聞 |
林大地、今季6点目 ベルギー1部、ゲンク戦 |
https://www.hokkaido-np.co.jp/article/656448/
|
林大地 |
2022-03-14 06:02:00 |
ビジネス |
東洋経済オンライン |
2020年代の社会保障改革へ岸田政権の「本気度」 財務省・厚労省のエース級幹部を事務局に配置 | 岐路に立つ日本の財政 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/538312?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
岸田文雄 |
2022-03-14 06:30:00 |
コメント
コメントを投稿