Upgrade to Prettier 2 (#13061)

This commit is contained in:
Joe Haddad 2020-05-18 15:24:37 -04:00 committed by GitHub
parent 7c68d0c7f6
commit 86160a5190
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
595 changed files with 1525 additions and 1657 deletions

View file

@ -7,7 +7,4 @@ packages/react-refresh-utils/**/*.js
packages/react-refresh-utils/**/*.d.ts
packages/react-dev-overlay/lib/**
**/__tmp__/**
# prettier can't handle the `import type {} from ''` syntax yet
test/integration/typescript-only-remove-type-imports/**/*.ts
test/integration/typescript-only-remove-type-imports/**/*.tsx
lerna.json

View file

@ -2,7 +2,4 @@
**/_next/**
**/dist/**
packages/next/compiled/**/*
# prettier can't handle the `import type {} from ''` syntax yet
test/integration/typescript-only-remove-type-imports/**/*.ts
test/integration/typescript-only-remove-type-imports/**/*.tsx
lerna.json

View file

@ -20,7 +20,7 @@ const createSrcFolder = async () => {
join(srcDir, `folder${i % 5}`, `folder${i + (1 % 5)}`, `file${i}`)
)
await Promise.all(files.map(file => fs.outputFile(file, 'hello')))
await Promise.all(files.map((file) => fs.outputFile(file, 'hello')))
}
async function run(fn) {

View file

@ -71,9 +71,9 @@ class MyDocument extends Document {
ctx.renderPage = () =>
originalRenderPage({
// useful for wrapping the whole react tree
enhanceApp: App => App,
enhanceApp: (App) => App,
// useful for wrapping in a per-page basis
enhanceComponent: Component => Component,
enhanceComponent: (Component) => Component,
})
// Run the parent `getInitialProps`, it now includes the custom `renderPage`

View file

@ -45,7 +45,7 @@ app.prepare().then(() => {
} else {
handle(req, res, parsedUrl)
}
}).listen(3000, err => {
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})

View file

@ -55,7 +55,7 @@ To dynamically import the `Hello` component, you can return it from the [Promise
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() =>
import('../components/hello').then(mod => mod.Hello)
import('../components/hello').then((mod) => mod.Hello)
)
function Home() {

View file

@ -29,7 +29,7 @@ function Page({ stars }) {
return <div>Next stars: {stars}</div>
}
Page.getInitialProps = async ctx => {
Page.getInitialProps = async (ctx) => {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
return { stars: json.stargazers_count }

View file

@ -24,7 +24,7 @@ module.exports = {
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
},
webpackDevMiddleware: config => {
webpackDevMiddleware: (config) => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config

View file

@ -23,7 +23,7 @@ Open `next.config.js` and add the following `exportPathMap` config:
```js
module.exports = {
exportPathMap: async function(
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {

View file

@ -67,7 +67,7 @@ A `Link` to a dynamic route is a combination of the `href` and `as` props. A lin
```jsx
const pids = ['id1', 'id2', 'id3']
{
pids.map(pid => (
pids.map((pid) => (
<Link href="/post/[pid]" as={`/post/${pid}`}>
<a>Post {pid}</a>
</Link>

View file

@ -20,7 +20,7 @@ function ActiveLink({ children, href }) {
color: router.pathname === href ? 'red' : 'black',
}
const handleClick = e => {
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
@ -178,7 +178,7 @@ import { useCallback, useEffect } from 'react'
import Router from 'next/router'
export default function Login() {
const handleSubmit = useCallback(e => {
const handleSubmit = useCallback((e) => {
e.preventDefault()
fetch('/api/login', {
@ -187,7 +187,7 @@ export default function Login() {
body: JSON.stringify({
/* Form data */
}),
}).then(res => {
}).then((res) => {
// Do a fast client-side transition to the already prefetched dashboard page
if (res.ok) Router.push('/dashboard')
})
@ -283,7 +283,7 @@ For example, to listen to the router event `routeChangeStart`, do the following:
```jsx
import Router from 'next/router'
const handleRouteChange = url => {
const handleRouteChange = (url) => {
console.log('App is changing to: ', url)
}
@ -316,7 +316,7 @@ Router events should be registered when a component mounts ([useEffect](https://
import Router from 'next/router'
useEffect(() => {
const handleRouteChange = url => {
const handleRouteChange = (url) => {
console.log('App is changing to: ', url)
}

View file

@ -94,7 +94,7 @@ const cors = Cors({
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, result => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}

View file

@ -56,7 +56,7 @@ Heres an example which uses `getStaticProps` to fetch a list of blog posts fr
function Blog({ posts }) {
return (
<ul>
{posts.map(post => (
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
@ -100,7 +100,7 @@ For TypeScript, you can use the `GetStaticProps` type from `next`:
```ts
import { GetStaticProps } from 'next'
export const getStaticProps: GetStaticProps = async context => {
export const getStaticProps: GetStaticProps = async (context) => {
// ...
}
```
@ -123,7 +123,7 @@ import path from 'path'
function Blog({ posts }) {
return (
<ul>
{posts.map(post => (
{posts.map((post) => (
<li>
<h3>{post.filename}</h3>
<p>{post.content}</p>
@ -140,7 +140,7 @@ export async function getStaticProps() {
const postsDirectory = path.join(process.cwd(), 'posts')
const filenames = fs.readdirSync(postsDirectory)
const posts = filenames.map(filename => {
const posts = filenames.map((filename) => {
const filePath = path.join(postsDirectory, filename)
const fileContents = fs.readFileSync(filePath, 'utf8')
@ -260,7 +260,7 @@ export async function getStaticPaths() {
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map(post => ({
const paths = posts.map((post) => ({
params: { id: post.id },
}))
@ -445,7 +445,7 @@ For TypeScript, you can use the `GetServerSideProps` type from `next`:
```ts
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async context => {
export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}
```

View file

@ -93,7 +93,7 @@ Some pages require fetching external data for pre-rendering. There are two scena
function Blog({ posts }) {
return (
<ul>
{posts.map(post => (
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
@ -152,7 +152,7 @@ export async function getStaticPaths() {
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map(post => `/posts/${post.id}`)
const paths = posts.map((post) => `/posts/${post.id}`)
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.

View file

@ -54,7 +54,7 @@ For `getStaticProps`, `getStaticPaths`, and `getServerSideProps`, you can use th
```ts
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
export const getStaticProps: GetStaticProps = async context => {
export const getStaticProps: GetStaticProps = async (context) => {
// ...
}
@ -62,7 +62,7 @@ export const getStaticPaths: GetStaticPaths = async () => {
// ...
}
export const getServerSideProps: GetServerSideProps = async context => {
export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}
```

View file

@ -90,7 +90,7 @@ The `as` prop can also be generated dynamically. For example, to show a list of
function Home({ posts }) {
return (
<ul>
{posts.map(post => (
{posts.map((post) => (
<li key={post.id}>
<Link href="/blog/[slug]" as={`/blog/${post.slug}`}>
<a>{post.title}</a>

View file

@ -171,8 +171,8 @@ import dynamic from 'next/dynamic'
const HelloBundle = dynamic({
modules: () => {
const components = {
Hello1: () => import('../components/hello1').then(m => m.default),
Hello2: () => import('../components/hello2').then(m => m.default),
Hello1: () => import('../components/hello1').then((m) => m.default),
Hello2: () => import('../components/hello2').then((m) => m.default),
}
return components

View file

@ -11,7 +11,7 @@ Change your `exportPathMap` function in `next.config.js` to have a path that mat
```js
module.exports = {
exportPathMap: function() {
exportPathMap: function () {
return {
'/': { page: '/' },
// '/blog/nextjs': { page: '/blog/[post]/comment/[id]' }, // wrong

View file

@ -23,7 +23,7 @@ export default class YourEntryComponent extends React.Component {
or
```js
const YourEntryComponent = function() {
const YourEntryComponent = function () {
return 'foo'
}

View file

@ -18,8 +18,8 @@ import dynamic from 'next/dynamic'
const HelloBundle = dynamic({
modules: () => {
const components = {
Hello1: () => import('../components/hello1').then(m => m.default),
Hello2: () => import('../components/hello2').then(m => m.default),
Hello1: () => import('../components/hello1').then((m) => m.default),
Hello2: () => import('../components/hello2').then((m) => m.default),
}
return components

View file

@ -5,7 +5,7 @@ Due to [this bug fix](https://github.com/zeit/next.js/pull/3849), we had to remo
We use this hook to detect a new app deployment when switching pages and act accordingly. Although there are many things you can do in this hook, it's often used to navigate the page via the server as shown below:
```js
Router.onAppUpdated = function(nextRoute) {
Router.onAppUpdated = function (nextRoute) {
location.href = nextRoute
}
```
@ -17,7 +17,7 @@ One real use of this hook is to persist your application state to local-storage
This is code for that:
```js
window.onbeforeunload = function(e) {
window.onbeforeunload = function (e) {
// Get the application state (usually from a store like Redux)
const appState = {}
localStorage.setItem('app-state', JSON.stringify(appState))

View file

@ -6,7 +6,7 @@ The webpack function in `next.config.js` returned a promise which is not support
```js
module.exports = {
webpack: async function(config) {
webpack: async function (config) {
return config
},
}

View file

@ -10,7 +10,7 @@ const THEME_COLOR = '#005af0'
*
* @param {Props} props
*/
const Layout = props => (
const Layout = (props) => (
<>
<NextHead>
<title>{props.title || ''}</title>

View file

@ -9,7 +9,7 @@ import {
export const config = { amp: true }
const Home = props => (
const Home = (props) => (
<>
<Layout
title="Welcome to AMP"

View file

@ -37,7 +37,7 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
WithApollo.getInitialProps = async (ctx) => {
const { AppTree } = ctx
// Initialize ApolloClient, add it to the ctx object so

View file

@ -31,7 +31,7 @@ export const resolvers = {
try {
const { id, email } = jwt.verify(token, JWT_SECRET)
return users.find(user => user.id === id && user.email === email)
return users.find((user) => user.id === id && user.email === email)
} catch {
throw new AuthenticationError(
'Authentication token is invalid, please log in'
@ -50,7 +50,7 @@ export const resolvers = {
},
async signIn(_parent, args, context, _info) {
const user = users.find(user => user.email === args.input.email)
const user = users.find((user) => user.email === args.input.email)
if (user && validPassword(user, args.input.password)) {
const token = jwt.sign(

View file

@ -37,7 +37,7 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
WithApollo.getInitialProps = async (ctx) => {
const { AppTree } = ctx
// Initialize ApolloClient, add it to the ctx object so

View file

@ -3,7 +3,7 @@
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, result => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}

View file

@ -1,6 +1,6 @@
import useSWR from 'swr'
const fetcher = query =>
const fetcher = (query) =>
fetch('/api/graphql', {
method: 'POST',
headers: {
@ -8,8 +8,8 @@ const fetcher = query =>
},
body: JSON.stringify({ query }),
})
.then(res => res.json())
.then(json => json.data)
.then((res) => res.json())
.then((json) => json.data)
export default function Index() {
const { data, error } = useSWR('{ users { name } }', fetcher)

View file

@ -1,6 +1,6 @@
import useSWR from 'swr'
const fetcher = url => fetch(url).then(res => res.text())
const fetcher = (url) => fetch(url).then((res) => res.text())
export default function Index() {
const { data, error } = useSWR('/api/cookies', fetcher)

View file

@ -18,7 +18,7 @@ const cookie = (res, name, value, options = {}) => {
/**
* Adds `cookie` function on `res.cookie` to set cookies for response
*/
const cookies = handler => (req, res) => {
const cookies = (handler) => (req, res) => {
res.cookie = (name, value, options) => cookie(res, name, value, options)
return handler(req, res)

View file

@ -1,7 +1,7 @@
import useSwr from 'swr'
import Link from 'next/link'
const fetcher = url => fetch(url).then(res => res.json())
const fetcher = (url) => fetch(url).then((res) => res.json())
export default function Index() {
const { data, error } = useSwr('/api/users', fetcher)
@ -11,7 +11,7 @@ export default function Index() {
return (
<ul>
{data.map(user => (
{data.map((user) => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user.id}`}>
<a>{`User ${user.id}`}</a>

View file

@ -1,7 +1,7 @@
import { useRouter } from 'next/router'
import useSwr from 'swr'
const fetcher = url => fetch(url).then(res => res.json())
const fetcher = (url) => fetch(url).then((res) => res.json())
export default function User() {
const router = useRouter()

View file

@ -1,7 +1,7 @@
import { people } from '../../../data'
export default ({ query: { id } }, res) => {
const filtered = people.filter(p => p.id === id)
const filtered = people.filter((p) => p.id === id)
// User with id exists
if (filtered.length > 0) {

View file

@ -1,7 +1,7 @@
import useSWR from 'swr'
import Person from '../components/Person'
const fetcher = url => fetch(url).then(res => res.json())
const fetcher = (url) => fetch(url).then((res) => res.json())
export default function Index() {
const { data, error } = useSWR('/api/people', fetcher)

View file

@ -1,7 +1,7 @@
import { useRouter } from 'next/router'
import useSWR from 'swr'
const fetcher = async url => {
const fetcher = async (url) => {
const res = await fetch(url)
const data = await res.json()

View file

@ -48,7 +48,7 @@ export function useFetchUser({ required } = {}) {
setLoading(true)
let isMounted = true
fetchUser().then(user => {
fetchUser().then((user) => {
// Only set the user if the component is still mounted
if (isMounted) {
// When the user is not logged in but login is required

View file

@ -7,7 +7,7 @@ export default function MoreStories({ posts }) {
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
{posts.map(post => (
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}

View file

@ -17,7 +17,7 @@ export function getPostBySlug(slug, fields = []) {
const items = {}
// Ensure only the minimal needed data is exposed
fields.forEach(field => {
fields.forEach((field) => {
if (field === 'slug') {
items[field] = realSlug
}
@ -36,7 +36,7 @@ export function getPostBySlug(slug, fields = []) {
export function getAllPosts(fields = []) {
const slugs = getPostSlugs()
const posts = slugs
.map(slug => getPostBySlug(slug, fields))
.map((slug) => getPostBySlug(slug, fields))
// sort posts by date in descending order
.sort((post1, post2) => (post1.date > post2.date ? '-1' : '1'))
return posts

View file

@ -2,8 +2,6 @@ import remark from 'remark'
import html from 'remark-html'
export default async function markdownToHtml(markdown) {
const result = await remark()
.use(html)
.process(markdown)
const result = await remark().use(html).process(markdown)
return result.toString()
}

View file

@ -72,7 +72,7 @@ export async function getStaticPaths() {
const posts = getAllPosts(['slug'])
return {
paths: posts.map(posts => {
paths: posts.map((posts) => {
return {
params: {
slug: posts.slug,

View file

@ -7,7 +7,7 @@ export default function MoreStories({ posts }) {
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
{posts.map(post => (
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}

View file

@ -19,4 +19,4 @@ spaceImport({
content: exportFile,
})
.then(() => console.log('The content model of your space is set up!'))
.catch(e => console.error(e))
.catch((e) => console.error(e))

View file

@ -11,7 +11,7 @@ const previewClient = createClient({
host: 'preview.contentful.com',
})
const getClient = preview => (preview ? previewClient : client)
const getClient = (preview) => (preview ? previewClient : client)
function parseAuthor({ fields }) {
return {
@ -50,7 +50,7 @@ export async function getAllPostsWithSlug() {
content_type: 'post',
select: 'fields.slug',
})
return parsePostEntries(entries, post => post.fields)
return parsePostEntries(entries, (post) => post.fields)
}
export async function getAllPostsForHome(preview) {

View file

@ -9,7 +9,8 @@ module.exports = {
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
defaultExtractor: (content) =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
]
: undefined,

View file

@ -7,7 +7,7 @@ export default function MoreStories({ posts }) {
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
{posts.map(post => (
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}

View file

@ -2,8 +2,6 @@ import remark from 'remark'
import html from 'remark-html'
export default async function markdownToHtml(markdown) {
const result = await remark()
.use(html)
.processSync(markdown)
const result = await remark().use(html).processSync(markdown)
return result.toString()
}

View file

@ -69,7 +69,7 @@ export async function getStaticProps({ params, preview = false }) {
export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug()
return {
paths: allPosts?.map(post => `/posts/${post.slug}`) || [],
paths: allPosts?.map((post) => `/posts/${post.slug}`) || [],
fallback: true,
}
}

View file

@ -9,7 +9,8 @@ module.exports = {
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
defaultExtractor: (content) =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
]
: undefined,

View file

@ -9,7 +9,8 @@ module.exports = {
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
defaultExtractor: (content) =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
]
: undefined,

View file

@ -11,11 +11,7 @@ export default function CoverImage({ title, url, slug }) {
className={cn('shadow-small', {
'hover:shadow-medium transition-shadow duration-200': slug,
})}
src={imageBuilder
.image(url)
.height(1000)
.width(2000)
.url()}
src={imageBuilder.image(url).height(1000).width(2000).url()}
/>
)

View file

@ -7,7 +7,7 @@ export default function MoreStories({ posts }) {
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
{posts.map(post => (
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}

View file

@ -1,9 +1,9 @@
import client, { previewClient } from './sanity'
import sanityImage from '@sanity/image-url'
const getUniquePosts = posts => {
const getUniquePosts = (posts) => {
const slugs = new Set()
return posts.filter(post => {
return posts.filter((post) => {
if (slugs.has(post.slug)) {
return false
} else {
@ -23,7 +23,7 @@ const postFields = `
'author': author->{name, 'picture': picture.asset->url},
`
const getClient = preview => (preview ? previewClient : client)
const getClient = (preview) => (preview ? previewClient : client)
export const imageBuilder = sanityImage(client)
@ -62,7 +62,7 @@ export async function getPostAndMorePosts(slug, preview) {
}`,
{ slug }
)
.then(res => res?.[0]),
.then((res) => res?.[0]),
curClient.fetch(
`*[_type == "post" && slug.current != $slug] | order(date desc, _updatedAt desc){
${postFields}

View file

@ -64,7 +64,7 @@ export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug()
return {
paths:
allPosts?.map(post => ({
allPosts?.map((post) => ({
params: {
slug: post.slug,
},

View file

@ -10,7 +10,7 @@ module.exports = {
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content =>
defaultExtractor: (content) =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
],

View file

@ -7,7 +7,7 @@ export default function MoreStories({ posts }) {
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
{posts.map(post => (
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}

View file

@ -2,8 +2,6 @@ import remark from 'remark'
import html from 'remark-html'
export default async function markdownToHtml(markdown) {
const result = await remark()
.use(html)
.processSync(markdown)
const result = await remark().use(html).processSync(markdown)
return result.toString()
}

View file

@ -80,7 +80,7 @@ export async function getStaticProps({ params, preview = false }) {
export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug()
return {
paths: allPosts?.map(post => `/posts/${post.slug}`) || [],
paths: allPosts?.map((post) => `/posts/${post.slug}`) || [],
fallback: true,
}
}

View file

@ -9,7 +9,8 @@ module.exports = {
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
defaultExtractor: (content) =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
]
: undefined,

View file

@ -54,7 +54,7 @@ module.exports = class NextInitializer extends Initializer {
async initialize() {
api.next = {
render: async connection => {
render: async (connection) => {
if (connection.type !== 'web') {
throw new Error('Connections for NEXT apps must be of type "web"')
}
@ -111,7 +111,7 @@ Note that this is where the websocket server, if you enable it, will place the `
// config/routes.js
exports['default'] = {
routes: api => {
routes: (api) => {
return {
get: [
{ path: '/time', action: 'time' },

View file

@ -1,7 +1,7 @@
const path = require('path')
exports['default'] = {
general: api => {
general: (api) => {
const packageJSON = require(api.projectRoot + path.sep + 'package.json')
return {
@ -65,7 +65,7 @@ exports['default'] = {
}
exports.test = {
general: api => {
general: (api) => {
return {
id: 'test-server-' + process.pid,
serverToken: 'serverToken-' + process.pid,
@ -86,7 +86,7 @@ exports.test = {
}
exports.production = {
general: api => {
general: (api) => {
return {
fileRequestLogLevel: 'debug',
developmentMode: false,

View file

@ -1,6 +1,6 @@
// error messages can be strings of objects
exports['default'] = {
errors: api => {
errors: (api) => {
return {
_toExpand: false,
@ -10,28 +10,28 @@ exports['default'] = {
serializers: {
servers: {
web: error => {
web: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
websocket: error => {
websocket: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
socket: error => {
socket: (error) => {
if (error.message) {
return String(error.message)
} else {
return error
}
},
specHelper: error => {
specHelper: (error) => {
if (error.message) {
return 'Error: ' + String(error.message)
} else {
@ -62,12 +62,12 @@ exports['default'] = {
},
// user requested an unknown action
unknownAction: data => {
unknownAction: (data) => {
return data.connection.localize('actionhero.errors.unknownAction')
},
// action not useable by this client/server type
unsupportedServerType: data => {
unsupportedServerType: (data) => {
return data.connection.localize([
'actionhero.errors.unsupportedServerType',
{ type: data.connection.type },
@ -75,13 +75,13 @@ exports['default'] = {
},
// action failed because server is mid-shutdown
serverShuttingDown: data => {
serverShuttingDown: (data) => {
return data.connection.localize('actionhero.errors.serverShuttingDown')
},
// action failed because this client already has too many pending acitons
// limit defined in api.config.general.simultaneousActions
tooManyPendingActions: data => {
tooManyPendingActions: (data) => {
return data.connection.localize(
'actionhero.errors.tooManyPendingActions'
)
@ -100,12 +100,12 @@ exports['default'] = {
// The body message to accompany 404 (file not found) errors regarding flat files
// You may want to load in the contnet of 404.html or similar
fileNotFound: connection => {
fileNotFound: (connection) => {
return connection.localize(['actionhero.errors.fileNotFound'])
},
// user didn't request a file
fileNotProvided: connection => {
fileNotProvided: (connection) => {
return connection.localize('actionhero.errors.fileNotProvided')
},
@ -135,7 +135,7 @@ exports['default'] = {
])
},
connectionRoomAndMessage: connection => {
connectionRoomAndMessage: (connection) => {
return connection.localize('actionhero.errors.connectionRoomAndMessage')
},
@ -153,21 +153,21 @@ exports['default'] = {
])
},
connectionRoomHasBeenDeleted: room => {
connectionRoomHasBeenDeleted: (room) => {
return api.i18n.localize(
'actionhero.errors.connectionRoomHasBeenDeleted'
)
},
connectionRoomNotExist: room => {
connectionRoomNotExist: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomNotExist')
},
connectionRoomExists: room => {
connectionRoomExists: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomExists')
},
connectionRoomRequired: room => {
connectionRoomRequired: (room) => {
return api.i18n.localize('actionhero.errors.connectionRoomRequired')
},
}

View file

@ -1,5 +1,5 @@
exports['default'] = {
i18n: api => {
i18n: (api) => {
return {
// visit https://github.com/mashpie/i18n-node to see all configuration options
// locale path can be configired from within ./config/api.js
@ -28,7 +28,7 @@ exports['default'] = {
}
exports.test = {
i18n: api => {
i18n: (api) => {
return {
updateFiles: true,
}

View file

@ -2,16 +2,16 @@ const fs = require('fs')
const cluster = require('cluster')
exports['default'] = {
logger: api => {
logger: (api) => {
let logger = { transports: [] }
// console logger
if (cluster.isMaster) {
logger.transports.push(function(api, winston) {
logger.transports.push(function (api, winston) {
return new winston.transports.Console({
colorize: true,
level: 'info',
timestamp: function() {
timestamp: function () {
return api.id + ' @ ' + new Date().toISOString()
},
})
@ -19,7 +19,7 @@ exports['default'] = {
}
// file logger
logger.transports.push(function(api, winston) {
logger.transports.push(function (api, winston) {
if (api.config.general.paths.log.length === 1) {
const logDirectory = api.config.general.paths.log[0]
try {
@ -35,7 +35,7 @@ exports['default'] = {
filename:
api.config.general.paths.log[0] + '/' + api.pids.title + '.log',
level: 'info',
timestamp: function() {
timestamp: function () {
return api.id + ' @ ' + new Date().toISOString()
},
})
@ -55,7 +55,7 @@ exports['default'] = {
}
exports.test = {
logger: api => {
logger: (api) => {
return {
transports: null,
}

View file

@ -1,5 +1,5 @@
exports['default'] = {
plugins: api => {
plugins: (api) => {
/*
If you want to use plugins in your application, include them here:

View file

@ -11,7 +11,7 @@ if (process.env.REDIS_URL) {
}
exports['default'] = {
redis: api => {
redis: (api) => {
// konstructor: The redis client constructor method. All redis methods must be promises
// args: The arguments to pass to the constructor
// buildNew: is it `new konstructor()` or just `konstructor()`?

View file

@ -1,5 +1,5 @@
exports['default'] = {
routes: api => {
routes: (api) => {
return {
get: [{ path: '/', matchTrailingPathParts: true, action: 'render' }],
}

View file

@ -1,6 +1,6 @@
exports['default'] = {
servers: {
socket: api => {
socket: (api) => {
return {
enabled: process.env.ENABLE_TCP_SERVER !== undefined,
// TCP or TLS?
@ -24,7 +24,7 @@ exports['default'] = {
exports.test = {
servers: {
socket: api => {
socket: (api) => {
return {
enabled: true,
port: 1001 + (process.pid % 64535),

View file

@ -2,7 +2,7 @@ const os = require('os')
exports['default'] = {
servers: {
web: api => {
web: (api) => {
return {
enabled: true,
// HTTP or HTTPS?
@ -93,7 +93,7 @@ exports['default'] = {
exports.production = {
servers: {
web: api => {
web: (api) => {
return {
padding: null,
metadataOptions: {
@ -107,7 +107,7 @@ exports.production = {
exports.test = {
servers: {
web: api => {
web: (api) => {
return {
secure: false,
port: process.env.PORT || 1000 + (process.pid % 64535),

View file

@ -2,7 +2,7 @@
exports['default'] = {
servers: {
websocket: api => {
websocket: (api) => {
return {
enabled: true,
// you can pass a FQDN (string) here or 'window.location.origin'
@ -53,7 +53,7 @@ exports['default'] = {
exports['test'] = {
servers: {
websocket: api => {
websocket: (api) => {
return { clientUrl: null }
},
},

View file

@ -1,5 +1,5 @@
exports['default'] = {
tasks: api => {
tasks: (api) => {
return {
// Should this node run a scheduler to promote delayed tasks?
scheduler: false,
@ -52,7 +52,7 @@ exports['default'] = {
}
exports.test = {
tasks: api => {
tasks: (api) => {
return {
timeout: 100,
checkTimeout: 50,

View file

@ -9,7 +9,7 @@ module.exports = class NextInitializer extends Initializer {
async initialize() {
api.next = {
render: async connection => {
render: async (connection) => {
if (connection.type !== 'web') {
throw new Error('Connections for NEXT apps must be of type "web"')
}

View file

@ -21,7 +21,7 @@ app.prepare().then(() => {
return handle(req, res)
})
server.listen(port, err => {
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})

View file

@ -44,10 +44,10 @@ fastify.register((fastify, opts, next) => {
next()
})
.catch(err => next(err))
.catch((err) => next(err))
})
fastify.listen(port, err => {
fastify.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})

View file

@ -1,11 +1,14 @@
const nextHandlerWrapper = app => {
const nextHandlerWrapper = (app) => {
const handler = app.getRequestHandler()
return async ({ raw, url }, h) => {
await handler(raw.req, raw.res, url)
return h.close
}
}
const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }, h) => {
const defaultHandlerWrapper = (app) => async (
{ raw: { req, res }, url },
h
) => {
const { pathname, query } = url
const html = await app.renderToHTML(req, res, pathname, query)
return h.response(html).code(res.statusCode)

View file

@ -11,17 +11,17 @@ app.prepare().then(() => {
const server = new Koa()
const router = new Router()
router.get('/a', async ctx => {
router.get('/a', async (ctx) => {
await app.render(ctx.req, ctx.res, '/a', ctx.query)
ctx.respond = false
})
router.get('/b', async ctx => {
router.get('/b', async (ctx) => {
await app.render(ctx.req, ctx.res, '/b', ctx.query)
ctx.respond = false
})
router.all('*', async ctx => {
router.all('*', async (ctx) => {
await handle(ctx.req, ctx.res)
ctx.respond = false
})

View file

@ -15,7 +15,7 @@ app.prepare().then(() => {
server.all('*', (req, res) => handle(req, res))
server.listen(port, err => {
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})

View file

@ -18,7 +18,7 @@ app.prepare().then(() => {
} else {
handle(req, res, parsedUrl)
}
}).listen(port, err => {
}).listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})

View file

@ -1,6 +1,6 @@
import React from 'react'
export default function(props) {
export default function (props) {
return (
<div>
<h1>My {props.id} blog post</h1>

View file

@ -38,7 +38,7 @@ app.prepare().then(() => {
server.get('*', (req, res) => handle(req, res))
server.listen(port, err => {
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})

View file

@ -12,7 +12,7 @@ const Link = ({ children, href }) => {
return (
<a
href="#"
onClick={e => {
onClick={(e) => {
e.preventDefault()
// typically you want to use `next/link` for this usecase
// but this example shows how you can also access the router

View file

@ -6,7 +6,7 @@ const defaultDescription = ''
const defaultOGURL = ''
const defaultOGImage = ''
export const Head = props => (
export const Head = (props) => (
<NextHead>
<meta charSet="UTF-8" />
<title>{props.title || ''}</title>

View file

@ -1,5 +1,5 @@
module.exports = {
webpack: config => {
webpack: (config) => {
// Fixes npm packages that depend on `fs` module
config.node = {
fs: 'empty',

View file

@ -6,7 +6,7 @@ import qs from 'qs'
const updateAfter = 700
const searchStateToUrl = searchState =>
const searchStateToUrl = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : ''
export default class extends React.Component {
@ -33,7 +33,7 @@ export default class extends React.Component {
return { resultsState, searchState }
}
onSearchStateChange = searchState => {
onSearchStateChange = (searchState) => {
clearTimeout(this.debouncedSetState)
this.debouncedSetState = setTimeout(() => {
const href = searchStateToUrl(searchState)

View file

@ -1,4 +1,4 @@
const compose = plugins => ({
const compose = (plugins) => ({
webpack(config, options) {
return plugins.reduce((config, plugin) => {
if (plugin instanceof Array) {

View file

@ -2,7 +2,7 @@ import { useSelector, shallowEqual } from 'react-redux'
const useClock = () => {
return useSelector(
state => ({
(state) => ({
lastUpdate: state.lastUpdate,
light: state.light,
}),
@ -10,7 +10,7 @@ const useClock = () => {
)
}
const formatTime = time => {
const formatTime = (time) => {
// cut off except hh:mm:ss
return new Date(time).toJSON().slice(11, 19)
}

View file

@ -1,7 +1,7 @@
import { useSelector, useDispatch } from 'react-redux'
const useCounter = () => {
const count = useSelector(state => state.count)
const count = useSelector((state) => state.count)
const dispatch = useDispatch()
const increment = () =>
dispatch({

View file

@ -17,7 +17,7 @@ const CREATE_POST_MUTATION = gql`
const Submit = () => {
const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
const handleSubmit = event => {
const handleSubmit = (event) => {
event.preventDefault()
const form = event.target
const formData = new window.FormData(form)

View file

@ -37,7 +37,7 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
WithApollo.getInitialProps = async (ctx) => {
const { AppTree } = ctx
// Initialize ApolloClient, add it to the ctx object so

View file

@ -30,7 +30,7 @@ export const withRedux = (PageComponent, { ssr = true } = {}) => {
}
if (ssr || PageComponent.getInitialProps) {
WithRedux.getInitialProps = async context => {
WithRedux.getInitialProps = async (context) => {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const reduxStore = getOrInitializeStore()
@ -56,7 +56,7 @@ export const withRedux = (PageComponent, { ssr = true } = {}) => {
}
let reduxStore
const getOrInitializeStore = initialState => {
const getOrInitializeStore = (initialState) => {
// Always make a new store if server, otherwise state is shared between requests
if (typeof window === 'undefined') {
return initializeStore(initialState)

View file

@ -17,7 +17,7 @@ const CREATE_POST_MUTATION = gql`
export default function Submit() {
const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION)
const handleSubmit = event => {
const handleSubmit = (event) => {
event.preventDefault()
const form = event.target
const formData = new window.FormData(form)

View file

@ -13,7 +13,7 @@ let globalApolloClient = null
* inside getStaticProps, getStaticPaths or getServerSideProps
* @param {NextPageContext | NextAppContext} ctx
*/
export const initOnContext = ctx => {
export const initOnContext = (ctx) => {
const inAppContext = Boolean(ctx.ctx)
// We consider installing `withApollo({ ssr: true })` on global App level
@ -78,7 +78,7 @@ const initApolloClient = (initialState, ctx) => {
* @param {Boolean} [withApolloOptions.ssr=false]
* @returns {(PageComponent: ReactNode) => ReactNode}
*/
export const withApollo = ({ ssr = false } = {}) => PageComponent => {
export const withApollo = ({ ssr = false } = {}) => (PageComponent) => {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
let client
if (apolloClient) {
@ -104,7 +104,7 @@ export const withApollo = ({ ssr = false } = {}) => PageComponent => {
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
WithApollo.getInitialProps = async (ctx) => {
const inAppContext = Boolean(ctx.ctx)
const { apolloClient } = initOnContext(ctx)

View file

@ -5,7 +5,7 @@ import Submit from '../components/Submit'
import PostList from '../components/PostList'
import { withApollo } from '../lib/apollo'
const ClientOnlyPage = props => (
const ClientOnlyPage = (props) => (
<App>
<Header />
<InfoBox>

View file

@ -2,7 +2,7 @@ const withCSS = require('@zeit/next-css')
module.exports = withCSS({
cssModules: true,
webpack: config => {
webpack: (config) => {
config.module.rules.push({
test: /\.js$/,
use: ['astroturf/loader'],

View file

@ -9,7 +9,8 @@ export default class MyDocument extends Document {
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)

View file

@ -46,24 +46,24 @@ type Action =
const reducer: React.Reducer<State, Action> = (state, action) => {
switch (action.type) {
case 'add-todo': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.todos.push(action.payload)
})
}
case 'delete-todo': {
const index = state.todos.findIndex(({ id }) => action.payload === id)
if (index === -1) return state
return produce(state, draft => {
return produce(state, (draft) => {
draft.todos.splice(index, 1)
})
}
case 'reset-current': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.currentName = ''
})
}
case 'set-current': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.currentName = action.payload
})
}
@ -111,14 +111,14 @@ const App = (props: Props) => {
<div>
<h3>Add a Todo</h3>
<form
onSubmit={ev => {
onSubmit={(ev) => {
ev.preventDefault()
createToDo(dispatch, state.currentName)
}}
>
<input
value={state.currentName}
onChange={e => {
onChange={(e) => {
dispatch({ type: 'set-current', payload: e.target.value })
}}
/>

View file

@ -16,7 +16,7 @@ const TodoPage = (props: { todo: GetTodoQuery['getTodo'] }) => {
)
}
TodoPage.getInitialProps = async context => {
TodoPage.getInitialProps = async (context) => {
const { id } = context.query
try {
const todo = (await API.graphql({

View file

@ -17,24 +17,24 @@ API.configure(config)
const reducer = (state, action) => {
switch (action.type) {
case 'add-todo': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.todos.push(action.payload)
})
}
case 'delete-todo': {
const index = state.todos.findIndex(({ id }) => action.payload === id)
if (index === -1) return state
return produce(state, draft => {
return produce(state, (draft) => {
draft.todos.splice(index, 1)
})
}
case 'reset-current': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.currentName = ''
})
}
case 'set-current': {
return produce(state, draft => {
return produce(state, (draft) => {
draft.currentName = action.payload
})
}
@ -73,7 +73,7 @@ const deleteToDo = async (dispatch, id) => {
console.warn('Error deleting to do ', err)
}
}
const App = props => {
const App = (props) => {
const [state, dispatch] = React.useReducer(reducer, {
todos: props.todos,
currentName: '',
@ -82,14 +82,14 @@ const App = props => {
<div>
<h3>Add a Todo</h3>
<form
onSubmit={ev => {
onSubmit={(ev) => {
ev.preventDefault()
createToDo(dispatch, state.currentName)
}}
>
<input
value={state.currentName}
onChange={e => {
onChange={(e) => {
dispatch({ type: 'set-current', payload: e.target.value })
}}
/>

View file

@ -6,7 +6,7 @@ import config from '../../src/aws-exports'
API.configure(config)
const TodoPage = props => {
const TodoPage = (props) => {
return (
<div>
<h2>Individual Todo {props.todo.id}</h2>
@ -15,7 +15,7 @@ const TodoPage = props => {
)
}
TodoPage.getInitialProps = async context => {
TodoPage.getInitialProps = async (context) => {
const { id } = context.query
try {
const todo = await API.graphql({

View file

@ -23,11 +23,11 @@ function getUser() {
this.isLoading = true
ajax
.get('/user')
.then(user => {
.then((user) => {
this.data = user
this.isLoading = false
})
.catch(error => {
.catch((error) => {
this.error = error
this.isLoading = false
})

Some files were not shown because too many files have changed in this diff Show more