From 6b420321fcf635931e1046354533cb6d1f342d77 Mon Sep 17 00:00:00 2001 From: Aditya Sridhar Date: Fri, 3 Nov 2023 17:35:25 -0400 Subject: [PATCH 01/57] chore: initial commit --- .gitignore | 3 + api/db/schema.prisma | 18 + api/jest.config.js | 8 + api/package.json | 9 + api/server.config.js | 52 + .../requireAuth/requireAuth.test.ts | 18 + api/src/directives/requireAuth/requireAuth.ts | 25 + api/src/directives/skipAuth/skipAuth.test.ts | 10 + api/src/directives/skipAuth/skipAuth.ts | 16 + api/src/functions/graphql.ts | 19 + api/src/graphql/.keep | 0 api/src/lib/auth.ts | 25 + api/src/lib/db.ts | 21 + api/src/lib/logger.ts | 17 + api/src/services/.keep | 0 api/tsconfig.json | 36 + api/types/graphql.d.ts | 219 + docs/README.md | 122 + graphql.config.js | 5 + jest.config.js | 8 + package.json | 24 + prettier.config.js | 18 + redwood.toml | 21 + scripts/.keep | 0 scripts/seed.ts | 63 + scripts/tsconfig.json | 42 + web/jest.config.js | 8 + web/package.json | 26 + web/public/README.md | 35 + web/public/favicon.png | Bin 0 -> 1741 bytes web/public/robots.txt | 2 + web/src/App.tsx | 19 + web/src/Routes.tsx | 20 + web/src/components/.keep | 0 web/src/entry.client.tsx | 23 + web/src/index.css | 0 web/src/index.html | 15 + web/src/layouts/.keep | 0 .../pages/FatalErrorPage/FatalErrorPage.tsx | 57 + web/src/pages/NotFoundPage/NotFoundPage.tsx | 44 + web/tsconfig.json | 39 + web/vite.config.ts | 16 + yarn.lock | 20983 ++++++++++++++++ 43 files changed, 22086 insertions(+) create mode 100644 api/db/schema.prisma create mode 100644 api/jest.config.js create mode 100644 api/package.json create mode 100644 api/server.config.js create mode 100644 api/src/directives/requireAuth/requireAuth.test.ts create mode 100644 api/src/directives/requireAuth/requireAuth.ts create mode 100644 api/src/directives/skipAuth/skipAuth.test.ts create mode 100644 api/src/directives/skipAuth/skipAuth.ts create mode 100644 api/src/functions/graphql.ts create mode 100644 api/src/graphql/.keep create mode 100644 api/src/lib/auth.ts create mode 100644 api/src/lib/db.ts create mode 100644 api/src/lib/logger.ts create mode 100644 api/src/services/.keep create mode 100644 api/tsconfig.json create mode 100644 api/types/graphql.d.ts create mode 100644 docs/README.md create mode 100644 graphql.config.js create mode 100644 jest.config.js create mode 100644 package.json create mode 100644 prettier.config.js create mode 100644 redwood.toml create mode 100644 scripts/.keep create mode 100644 scripts/seed.ts create mode 100644 scripts/tsconfig.json create mode 100644 web/jest.config.js create mode 100644 web/package.json create mode 100644 web/public/README.md create mode 100644 web/public/favicon.png create mode 100644 web/public/robots.txt create mode 100644 web/src/App.tsx create mode 100644 web/src/Routes.tsx create mode 100644 web/src/components/.keep create mode 100644 web/src/entry.client.tsx create mode 100644 web/src/index.css create mode 100644 web/src/index.html create mode 100644 web/src/layouts/.keep create mode 100644 web/src/pages/FatalErrorPage/FatalErrorPage.tsx create mode 100644 web/src/pages/NotFoundPage/NotFoundPage.tsx create mode 100644 web/tsconfig.json create mode 100644 web/vite.config.ts create mode 100644 yarn.lock diff --git a/.gitignore b/.gitignore index c6bba591..e00a606e 100644 --- a/.gitignore +++ b/.gitignore @@ -128,3 +128,6 @@ dist .yarn/build-state.yml .yarn/install-state.gz .pnp.* + +# Mac defaults +.DS_Store diff --git a/api/db/schema.prisma b/api/db/schema.prisma new file mode 100644 index 00000000..3dea71a6 --- /dev/null +++ b/api/db/schema.prisma @@ -0,0 +1,18 @@ +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" + binaryTargets = "native" +} + +// Define your own datamodels here and run `yarn redwood prisma migrate dev` +// to create migrations for them and apply to your dev DB. +// TODO: Please remove the following example: +model UserExample { + id Int @id @default(autoincrement()) + email String @unique + name String? +} diff --git a/api/jest.config.js b/api/jest.config.js new file mode 100644 index 00000000..932fc82d --- /dev/null +++ b/api/jest.config.js @@ -0,0 +1,8 @@ +// More info at https://redwoodjs.com/docs/project-configuration-dev-test-build + +const config = { + rootDir: '../', + preset: '@redwoodjs/testing/config/jest/api', +} + +module.exports = config diff --git a/api/package.json b/api/package.json new file mode 100644 index 00000000..1ef60a7c --- /dev/null +++ b/api/package.json @@ -0,0 +1,9 @@ +{ + "name": "api", + "version": "0.0.0", + "private": true, + "dependencies": { + "@redwoodjs/api": "6.3.2", + "@redwoodjs/graphql-server": "6.3.2" + } +} diff --git a/api/server.config.js b/api/server.config.js new file mode 100644 index 00000000..73dca922 --- /dev/null +++ b/api/server.config.js @@ -0,0 +1,52 @@ +/** + * This file allows you to configure the Fastify Server settings + * used by the RedwoodJS dev server. + * + * It also applies when running RedwoodJS with `yarn rw serve`. + * + * For the Fastify server options that you can set, see: + * https://www.fastify.io/docs/latest/Reference/Server/#factory + * + * Examples include: logger settings, timeouts, maximum payload limits, and more. + * + * Note: This configuration does not apply in a serverless deploy. + */ + +/** @type {import('fastify').FastifyServerOptions} */ +const config = { + requestTimeout: 15_000, + logger: { + // Note: If running locally using `yarn rw serve` you may want to adjust + // the default non-development level to `info` + level: process.env.NODE_ENV === 'development' ? 'debug' : 'warn', + }, +} + +/** + * You can also register Fastify plugins and additional routes for the API and Web sides + * in the configureFastify function. + * + * This function has access to the Fastify instance and options, such as the side + * (web, api, or proxy) that is being configured and other settings like the apiRootPath + * of the functions endpoint. + * + * Note: This configuration does not apply in a serverless deploy. + */ + +/** @type {import('@redwoodjs/api-server/dist/types').FastifySideConfigFn} */ +const configureFastify = async (fastify, options) => { + if (options.side === 'api') { + fastify.log.trace({ custom: { options } }, 'Configuring api side') + } + + if (options.side === 'web') { + fastify.log.trace({ custom: { options } }, 'Configuring web side') + } + + return fastify +} + +module.exports = { + config, + configureFastify, +} diff --git a/api/src/directives/requireAuth/requireAuth.test.ts b/api/src/directives/requireAuth/requireAuth.test.ts new file mode 100644 index 00000000..0f01aa36 --- /dev/null +++ b/api/src/directives/requireAuth/requireAuth.test.ts @@ -0,0 +1,18 @@ +import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' + +import requireAuth from './requireAuth' + +describe('requireAuth directive', () => { + it('declares the directive sdl as schema, with the correct name', () => { + expect(requireAuth.schema).toBeTruthy() + expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') + }) + + it('requireAuth has stub implementation. Should not throw when current user', () => { + // If you want to set values in context, pass it through e.g. + // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) + const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) + + expect(mockExecution).not.toThrowError() + }) +}) diff --git a/api/src/directives/requireAuth/requireAuth.ts b/api/src/directives/requireAuth/requireAuth.ts new file mode 100644 index 00000000..77b31a70 --- /dev/null +++ b/api/src/directives/requireAuth/requireAuth.ts @@ -0,0 +1,25 @@ +import gql from 'graphql-tag' + +import type { ValidatorDirectiveFunc } from '@redwoodjs/graphql-server' +import { createValidatorDirective } from '@redwoodjs/graphql-server' + +import { requireAuth as applicationRequireAuth } from 'src/lib/auth' + +export const schema = gql` + """ + Use to check whether or not a user is authenticated and is associated + with an optional set of roles. + """ + directive @requireAuth(roles: [String]) on FIELD_DEFINITION +` + +type RequireAuthValidate = ValidatorDirectiveFunc<{ roles?: string[] }> + +const validate: RequireAuthValidate = ({ directiveArgs }) => { + const { roles } = directiveArgs + applicationRequireAuth({ roles }) +} + +const requireAuth = createValidatorDirective(schema, validate) + +export default requireAuth diff --git a/api/src/directives/skipAuth/skipAuth.test.ts b/api/src/directives/skipAuth/skipAuth.test.ts new file mode 100644 index 00000000..88d99a56 --- /dev/null +++ b/api/src/directives/skipAuth/skipAuth.test.ts @@ -0,0 +1,10 @@ +import { getDirectiveName } from '@redwoodjs/testing/api' + +import skipAuth from './skipAuth' + +describe('skipAuth directive', () => { + it('declares the directive sdl as schema, with the correct name', () => { + expect(skipAuth.schema).toBeTruthy() + expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') + }) +}) diff --git a/api/src/directives/skipAuth/skipAuth.ts b/api/src/directives/skipAuth/skipAuth.ts new file mode 100644 index 00000000..e85b94ae --- /dev/null +++ b/api/src/directives/skipAuth/skipAuth.ts @@ -0,0 +1,16 @@ +import gql from 'graphql-tag' + +import { createValidatorDirective } from '@redwoodjs/graphql-server' + +export const schema = gql` + """ + Use to skip authentication checks and allow public access. + """ + directive @skipAuth on FIELD_DEFINITION +` + +const skipAuth = createValidatorDirective(schema, () => { + return +}) + +export default skipAuth diff --git a/api/src/functions/graphql.ts b/api/src/functions/graphql.ts new file mode 100644 index 00000000..f395c3b0 --- /dev/null +++ b/api/src/functions/graphql.ts @@ -0,0 +1,19 @@ +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' + +export const handler = createGraphQLHandler({ + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, +}) diff --git a/api/src/graphql/.keep b/api/src/graphql/.keep new file mode 100644 index 00000000..e69de29b diff --git a/api/src/lib/auth.ts b/api/src/lib/auth.ts new file mode 100644 index 00000000..f98fe93a --- /dev/null +++ b/api/src/lib/auth.ts @@ -0,0 +1,25 @@ +/** + * Once you are ready to add authentication to your application + * you'll build out requireAuth() with real functionality. For + * now we just return `true` so that the calls in services + * have something to check against, simulating a logged + * in user that is allowed to access that service. + * + * See https://redwoodjs.com/docs/authentication for more info. + */ +export const isAuthenticated = () => { + return true +} + +export const hasRole = ({ roles }) => { + return roles !== undefined +} + +// This is used by the redwood directive +// in ./api/src/directives/requireAuth + +// Roles are passed in by the requireAuth directive if you have auth setup +// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars +export const requireAuth = ({ roles }) => { + return isAuthenticated() +} diff --git a/api/src/lib/db.ts b/api/src/lib/db.ts new file mode 100644 index 00000000..5006d00a --- /dev/null +++ b/api/src/lib/db.ts @@ -0,0 +1,21 @@ +// See https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/constructor +// for options. + +import { PrismaClient } from '@prisma/client' + +import { emitLogLevels, handlePrismaLogging } from '@redwoodjs/api/logger' + +import { logger } from './logger' + +/* + * Instance of the Prisma Client + */ +export const db = new PrismaClient({ + log: emitLogLevels(['info', 'warn', 'error']), +}) + +handlePrismaLogging({ + db, + logger, + logLevels: ['info', 'warn', 'error'], +}) diff --git a/api/src/lib/logger.ts b/api/src/lib/logger.ts new file mode 100644 index 00000000..150a3097 --- /dev/null +++ b/api/src/lib/logger.ts @@ -0,0 +1,17 @@ +import { createLogger } from '@redwoodjs/api/logger' + +/** + * Creates a logger with RedwoodLoggerOptions + * + * These extend and override default LoggerOptions, + * can define a destination like a file or other supported pino log transport stream, + * and sets whether or not to show the logger configuration settings (defaults to false) + * + * @param RedwoodLoggerOptions + * + * RedwoodLoggerOptions have + * @param {options} LoggerOptions - defines how to log, such as redaction and format + * @param {string | DestinationStream} destination - defines where to log, such as a transport stream or file + * @param {boolean} showConfig - whether to display logger configuration on initialization + */ +export const logger = createLogger({}) diff --git a/api/src/services/.keep b/api/src/services/.keep new file mode 100644 index 00000000..e69de29b diff --git a/api/tsconfig.json b/api/tsconfig.json new file mode 100644 index 00000000..fcbbf987 --- /dev/null +++ b/api/tsconfig.json @@ -0,0 +1,36 @@ +{ + "compilerOptions": { + "noEmit": true, + "allowJs": true, + "esModuleInterop": true, + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "skipLibCheck": false, + "baseUrl": "./", + "rootDirs": [ + "./src", + "../.redwood/types/mirror/api/src" + ], + "paths": { + "src/*": [ + "./src/*", + "../.redwood/types/mirror/api/src/*" + ], + "types/*": ["./types/*", "../types/*"], + "@redwoodjs/testing": ["../node_modules/@redwoodjs/testing/api"] + }, + "typeRoots": [ + "../node_modules/@types", + "./node_modules/@types" + ], + "types": ["jest"], + "jsx": "react-jsx" + }, + "include": [ + "src", + "../.redwood/types/includes/all-*", + "../.redwood/types/includes/api-*", + "../types" + ] +} diff --git a/api/types/graphql.d.ts b/api/types/graphql.d.ts new file mode 100644 index 00000000..f04fca15 --- /dev/null +++ b/api/types/graphql.d.ts @@ -0,0 +1,219 @@ +import { Prisma } from "@prisma/client" +import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api' +import { UserExample as PrismaUserExample } from '@prisma/client' +import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; +import { RedwoodGraphQLContext } from '@redwoodjs/graphql-server/dist/types'; +export type Maybe = T | null; +export type InputMaybe = Maybe; +export type Exact = { [K in keyof T]: T[K] }; +export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; +export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; +export type ResolverFn = ( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise +export type OptArgsResolverFn = ( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise + + export type RequiredResolverFn = ( + args: TArgs, + obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise +/** All built-in and custom scalars, mapped to their actual values */ +export type Scalars = { + ID: string; + String: string; + Boolean: boolean; + Int: number; + Float: number; + BigInt: number; + Date: Date | string; + DateTime: Date | string; + JSON: Prisma.JsonValue; + JSONObject: Prisma.JsonObject; + Time: Date | string; +}; + +/** About the Redwood queries. */ +export type Query = { + __typename?: 'Query'; + /** Fetches the Redwood root schema. */ + redwood?: Maybe; +}; + +/** + * The RedwoodJS Root Schema + * + * Defines details about RedwoodJS such as the current user and version information. + */ +export type Redwood = { + __typename?: 'Redwood'; + /** The current user. */ + currentUser?: Maybe; + /** The version of Prisma. */ + prismaVersion?: Maybe; + /** The version of Redwood. */ + version?: Maybe; +}; + +type MaybeOrArrayOfMaybe = T | Maybe | Maybe[]; +type AllMappedModels = MaybeOrArrayOfMaybe<> + + +export type ResolverTypeWrapper = Promise | T; + +export type Resolver = ResolverFn; + +export type SubscriptionSubscribeFn = ( + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => AsyncIterable | Promise>; + +export type SubscriptionResolveFn = ( + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => TResult | Promise; + +export interface SubscriptionSubscriberObject { + subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; + resolve?: SubscriptionResolveFn; +} + +export interface SubscriptionResolverObject { + subscribe: SubscriptionSubscribeFn; + resolve: SubscriptionResolveFn; +} + +export type SubscriptionObject = + | SubscriptionSubscriberObject + | SubscriptionResolverObject; + +export type SubscriptionResolver = + | ((...args: any[]) => SubscriptionObject) + | SubscriptionObject; + +export type TypeResolveFn = ( + parent: TParent, + context: TContext, + info: GraphQLResolveInfo +) => Maybe | Promise>; + +export type IsTypeOfResolverFn = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise; + +export type NextResolverFn = () => Promise; + +export type DirectiveResolverFn = ( + next: NextResolverFn, + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => TResult | Promise; + + + +/** Mapping between all available schema types and the resolvers types */ +export type ResolversTypes = { + BigInt: ResolverTypeWrapper; + Boolean: ResolverTypeWrapper; + Date: ResolverTypeWrapper; + DateTime: ResolverTypeWrapper; + JSON: ResolverTypeWrapper; + JSONObject: ResolverTypeWrapper; + Query: ResolverTypeWrapper<{}>; + Redwood: ResolverTypeWrapper; + String: ResolverTypeWrapper; + Time: ResolverTypeWrapper; +}; + +/** Mapping between all available schema types and the resolvers parents */ +export type ResolversParentTypes = { + BigInt: Scalars['BigInt']; + Boolean: Scalars['Boolean']; + Date: Scalars['Date']; + DateTime: Scalars['DateTime']; + JSON: Scalars['JSON']; + JSONObject: Scalars['JSONObject']; + Query: {}; + Redwood: Redwood; + String: Scalars['String']; + Time: Scalars['Time']; +}; + +export type requireAuthDirectiveArgs = { + roles?: Maybe>>; +}; + +export type requireAuthDirectiveResolver = DirectiveResolverFn; + +export type skipAuthDirectiveArgs = { }; + +export type skipAuthDirectiveResolver = DirectiveResolverFn; + +export interface BigIntScalarConfig extends GraphQLScalarTypeConfig { + name: 'BigInt'; +} + +export interface DateScalarConfig extends GraphQLScalarTypeConfig { + name: 'Date'; +} + +export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig { + name: 'DateTime'; +} + +export interface JSONScalarConfig extends GraphQLScalarTypeConfig { + name: 'JSON'; +} + +export interface JSONObjectScalarConfig extends GraphQLScalarTypeConfig { + name: 'JSONObject'; +} + +export type QueryResolvers = { + redwood: OptArgsResolverFn, ParentType, ContextType>; +}; + +export type QueryRelationResolvers = { + redwood?: RequiredResolverFn, ParentType, ContextType>; +}; + +export type RedwoodResolvers = { + currentUser: OptArgsResolverFn, ParentType, ContextType>; + prismaVersion: OptArgsResolverFn, ParentType, ContextType>; + version: OptArgsResolverFn, ParentType, ContextType>; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export type RedwoodRelationResolvers = { + currentUser?: RequiredResolverFn, ParentType, ContextType>; + prismaVersion?: RequiredResolverFn, ParentType, ContextType>; + version?: RequiredResolverFn, ParentType, ContextType>; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export interface TimeScalarConfig extends GraphQLScalarTypeConfig { + name: 'Time'; +} + +export type Resolvers = { + BigInt: GraphQLScalarType; + Date: GraphQLScalarType; + DateTime: GraphQLScalarType; + JSON: GraphQLScalarType; + JSONObject: GraphQLScalarType; + Query: QueryResolvers; + Redwood: RedwoodResolvers; + Time: GraphQLScalarType; +}; + +export type DirectiveResolvers = { + requireAuth: requireAuthDirectiveResolver; + skipAuth: skipAuthDirectiveResolver; +}; diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..08f58865 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,122 @@ +# README + +Welcome to [RedwoodJS](https://redwoodjs.com)! + +> **Prerequisites** +> +> - Redwood requires [Node.js](https://nodejs.org/en/) (=18.x) and [Yarn](https://yarnpkg.com/) (>=1.15) +> - Are you on Windows? For best results, follow our [Windows development setup](https://redwoodjs.com/docs/how-to/windows-development-setup) guide + +Start by installing dependencies: + +``` +yarn install +``` + +Then start the development server: + +``` +yarn redwood dev +``` + +Your browser should automatically open to [http://localhost:8910](http://localhost:8910) where you'll see the Welcome Page, which links out to many great resources. + +> **The Redwood CLI** +> +> Congratulations on running your first Redwood CLI command! From dev to deploy, the CLI is with you the whole way. And there's quite a few commands at your disposal: +> +> ``` +> yarn redwood --help +> ``` +> +> For all the details, see the [CLI reference](https://redwoodjs.com/docs/cli-commands). + +## Prisma and the database + +Redwood wouldn't be a full-stack framework without a database. It all starts with the schema. Open the [`schema.prisma`](api/db/schema.prisma) file in `api/db` and replace the `UserExample` model with the following `Post` model: + +```prisma +model Post { + id Int @id @default(autoincrement()) + title String + body String + createdAt DateTime @default(now()) +} +``` + +Redwood uses [Prisma](https://www.prisma.io/), a next-gen Node.js and TypeScript ORM, to talk to the database. Prisma's schema offers a declarative way of defining your app's data models. And Prisma [Migrate](https://www.prisma.io/migrate) uses that schema to make database migrations hassle-free: + +``` +yarn rw prisma migrate dev + +# ... + +? Enter a name for the new migration: › create posts +``` + +> `rw` is short for `redwood` + +You'll be prompted for the name of your migration. `create posts` will do. + +Now let's generate everything we need to perform all the CRUD (Create, Retrieve, Update, Delete) actions on our `Post` model: + +``` +yarn redwood generate scaffold post +``` + +Navigate to [http://localhost:8910/posts/new](http://localhost:8910/posts/new), fill in the title and body, and click "Save". + +Did we just create a post in the database? Yup! With `yarn rw generate scaffold `, Redwood created all the pages, components, and services necessary to perform all CRUD actions on our posts table. + +## Frontend first with Storybook + +Don't know what your data models look like? That's more than ok—Redwood integrates Storybook so that you can work on design without worrying about data. Mockup, build, and verify your React components, even in complete isolation from the backend: + +``` +yarn rw storybook +``` + +Seeing "Couldn't find any stories"? That's because you need a `*.stories.{tsx,jsx}` file. The Redwood CLI makes getting one easy enough—try generating a [Cell](https://redwoodjs.com/docs/cells), Redwood's data-fetching abstraction: + +``` +yarn rw generate cell examplePosts +``` + +The Storybook server should hot reload and now you'll have four stories to work with. They'll probably look a little bland since there's no styling. See if the Redwood CLI's `setup ui` command has your favorite styling library: + +``` +yarn rw setup ui --help +``` + +## Testing with Jest + +It'd be hard to scale from side project to startup without a few tests. Redwood fully integrates Jest with both the front- and back-ends, and makes it easy to keep your whole app covered by generating test files with all your components and services: + +``` +yarn rw test +``` + +To make the integration even more seamless, Redwood augments Jest with database [scenarios](https://redwoodjs.com/docs/testing#scenarios) and [GraphQL mocking](https://redwoodjs.com/docs/testing#mocking-graphql-calls). + +## Ship it + +Redwood is designed for both serverless deploy targets like Netlify and Vercel and serverful deploy targets like Render and AWS: + +``` +yarn rw setup deploy --help +``` + +Don't go live without auth! Lock down your app with Redwood's built-in, database-backed authentication system ([dbAuth](https://redwoodjs.com/docs/authentication#self-hosted-auth-installation-and-setup)), or integrate with nearly a dozen third-party auth providers: + +``` +yarn rw setup auth --help +``` + +## Next Steps + +The best way to learn Redwood is by going through the comprehensive [tutorial](https://redwoodjs.com/docs/tutorial/foreword) and joining the community (via the [Discourse forum](https://community.redwoodjs.com) or the [Discord server](https://discord.gg/redwoodjs)). + +## Quick Links + +- Stay updated: read [Forum announcements](https://community.redwoodjs.com/c/announcements/5), follow us on [Twitter](https://twitter.com/redwoodjs), and subscribe to the [newsletter](https://redwoodjs.com/newsletter) +- [Learn how to contribute](https://redwoodjs.com/docs/contributing) diff --git a/graphql.config.js b/graphql.config.js new file mode 100644 index 00000000..2da7862f --- /dev/null +++ b/graphql.config.js @@ -0,0 +1,5 @@ +const { getPaths } = require('@redwoodjs/internal') + +module.exports = { + schema: getPaths().generated.schema, +} diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 00000000..c6b395cb --- /dev/null +++ b/jest.config.js @@ -0,0 +1,8 @@ +// This the Redwood root jest config +// Each side, e.g. ./web/ and ./api/ has specific config that references this root +// More info at https://redwoodjs.com/docs/project-configuration-dev-test-build + +module.exports = { + rootDir: '.', + projects: ['/{*,!(node_modules)/**/}/jest.config.js'], +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..2e4974a0 --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "private": true, + "workspaces": { + "packages": [ + "api", + "web" + ] + }, + "devDependencies": { + "@redwoodjs/core": "6.3.2" + }, + "eslintConfig": { + "extends": "@redwoodjs/eslint-config", + "root": true + }, + "engines": { + "node": "=18.x", + "yarn": ">=1.15" + }, + "prisma": { + "seed": "yarn rw exec seed" + }, + "packageManager": "yarn@3.6.3" +} diff --git a/prettier.config.js b/prettier.config.js new file mode 100644 index 00000000..45058f7a --- /dev/null +++ b/prettier.config.js @@ -0,0 +1,18 @@ +// https://prettier.io/docs/en/options.html +/** @type {import('prettier').RequiredOptions} */ +module.exports = { + trailingComma: 'es5', + bracketSpacing: true, + tabWidth: 2, + semi: false, + singleQuote: true, + arrowParens: 'always', + overrides: [ + { + files: 'Routes.*', + options: { + printWidth: 999, + }, + }, + ], +} diff --git a/redwood.toml b/redwood.toml new file mode 100644 index 00000000..147631de --- /dev/null +++ b/redwood.toml @@ -0,0 +1,21 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = 8910 + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = 8911 +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/scripts/.keep b/scripts/.keep new file mode 100644 index 00000000..e69de29b diff --git a/scripts/seed.ts b/scripts/seed.ts new file mode 100644 index 00000000..ecfa0b1a --- /dev/null +++ b/scripts/seed.ts @@ -0,0 +1,63 @@ +import type { Prisma } from '@prisma/client' +import { db } from 'api/src/lib/db' + +export default async () => { + try { + // + // Manually seed via `yarn rw prisma db seed` + // Seeds automatically with `yarn rw prisma migrate dev` and `yarn rw prisma migrate reset` + // + // Update "const data = []" to match your data model and seeding needs + // + const data: Prisma.UserExampleCreateArgs['data'][] = [ + // To try this example data with the UserExample model in schema.prisma, + // uncomment the lines below and run 'yarn rw prisma migrate dev' + // + // { name: 'alice', email: 'alice@example.com' }, + // { name: 'mark', email: 'mark@example.com' }, + // { name: 'jackie', email: 'jackie@example.com' }, + // { name: 'bob', email: 'bob@example.com' }, + ] + console.log( + "\nUsing the default './scripts/seed.{js,ts}' template\nEdit the file to add seed data\n" + ) + + // Note: if using PostgreSQL, using `createMany` to insert multiple records is much faster + // @see: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#createmany + await Promise.all( + // + // Change to match your data model and seeding needs + // + data.map(async (data: Prisma.UserExampleCreateArgs['data']) => { + const record = await db.userExample.create({ data }) + console.log(record) + }) + ) + + // If using dbAuth and seeding users, you'll need to add a `hashedPassword` + // and associated `salt` to their record. Here's how to create them using + // the same algorithm that dbAuth uses internally: + // + // import { hashPassword } from '@redwoodjs/auth-dbauth-api' + // + // const users = [ + // { name: 'john', email: 'john@example.com', password: 'secret1' }, + // { name: 'jane', email: 'jane@example.com', password: 'secret2' } + // ] + // + // for (const user of users) { + // const [hashedPassword, salt] = hashPassword(user.password) + // await db.user.create({ + // data: { + // name: user.name, + // email: user.email, + // hashedPassword, + // salt + // } + // }) + // } + } catch (error) { + console.warn('Please define your seed data.') + console.error(error) + } +} diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 00000000..babc7c43 --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,42 @@ +{ + "compilerOptions": { + "noEmit": true, + "allowJs": true, + "esModuleInterop": true, + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "baseUrl": "./", + "paths": { + "$api/*": [ + "../api/*" + ], + "api/*": [ + "../api/*" + ], + "$web/*": [ + "../web/*" + ], + "web/*": [ + "../web/*" + ], + "$web/src/*": [ + "../web/src/*", + "../.redwood/types/mirror/web/src/*" + ], + "web/src/*": [ + "../web/src/*", + "../.redwood/types/mirror/web/src/*" + ], + "types/*": ["../types/*", "../web/types/*", "../api/types/*"] + }, + "typeRoots": ["../node_modules/@types"], + "jsx": "preserve" + }, + "include": [ + ".", + "../.redwood/types/includes/all-*", + "../.redwood/types/includes/web-*", + "../types" + ] +} diff --git a/web/jest.config.js b/web/jest.config.js new file mode 100644 index 00000000..0e54869e --- /dev/null +++ b/web/jest.config.js @@ -0,0 +1,8 @@ +// More info at https://redwoodjs.com/docs/project-configuration-dev-test-build + +const config = { + rootDir: '../', + preset: '@redwoodjs/testing/config/jest/web', +} + +module.exports = config diff --git a/web/package.json b/web/package.json new file mode 100644 index 00000000..97b4bcae --- /dev/null +++ b/web/package.json @@ -0,0 +1,26 @@ +{ + "name": "web", + "version": "0.0.0", + "private": true, + "browserslist": { + "development": [ + "last 1 version" + ], + "production": [ + "defaults" + ] + }, + "dependencies": { + "@redwoodjs/forms": "6.3.2", + "@redwoodjs/router": "6.3.2", + "@redwoodjs/web": "6.3.2", + "prop-types": "15.8.1", + "react": "18.2.0", + "react-dom": "18.2.0" + }, + "devDependencies": { + "@redwoodjs/vite": "6.3.2", + "@types/react": "18.2.14", + "@types/react-dom": "18.2.6" + } +} diff --git a/web/public/README.md b/web/public/README.md new file mode 100644 index 00000000..618395f0 --- /dev/null +++ b/web/public/README.md @@ -0,0 +1,35 @@ +# Static Assets +Use this folder to add static files directly to your app. All included files and folders will be copied directly into the `/dist` folder (created when Vite builds for production). They will also be available during development when you run `yarn rw dev`. +>Note: files will *not* hot reload while the development server is running. You'll need to manually stop/start to access file changes. + +### Example Use +A file like `favicon.png` will be copied to `/dist/favicon.png`. A folder containing a file such as `static-files/my-logo.jpg` will be copied to `/dist/static-files/my-logo.jpg`. These can be referenced in your code directly without any special handling, e.g. +``` + +``` +and +``` + alt="Logo" /> +``` + + +## Best Practices +Because assets in this folder are bypassing the javascript module system, **this folder should be used sparingly** for assets such as favicons, robots.txt, manifests, libraries incompatible with Vite, etc. + +In general, it's best to import files directly into a template, page, or component. This allows Vite to include that file in the bundle when small enough, or to copy it over to the `dist` folder with a hash. + +### Example Asset Import with Vite +Instead of handling our logo image as a static file per the example above, we can do the following: +``` +import React from "react" +import logo from "./my-logo.jpg" + + +function Header() { + return Logo +} + +export default Header +``` + +See Vite's docs for [static asset handling](https://vitejs.dev/guide/assets.html) diff --git a/web/public/favicon.png b/web/public/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..47414294173cb0795dcafb8813599fc382282556 GIT binary patch literal 1741 zcmV;;1~U1HP)u3dvWaK1Jt7p7xtk~lm38V(vb%~9EcN4itP(!;||l>?RBBL}g^A8<`Fn z=_ofw?w2~Qt#0f9Ac3O;;Nt1}TFWmPb1YZ9hDBXZ zTK55jh;jRpRArCUs~@6m!BMLSuZE&5;HTqrDc^;f)?K|FaV6o1RTFbt+uA;);7z?5 z9axBZCgX!V;dhWl*HZCE&V7oz;oZ;*lOh^wZ2aYlLI<1rXkc0&HH!|5!S0|*s- zM*~yi#Ef4dES_G+_-z+`S<%x__Ulk8{Z?I!;wv8DmN?3t1H$+fJ*q^w!} z8`oOx{i(WL4oLgKN0~^gQyJ3t#+tnIhR=h}6@BVu1&_1g7*O6j$-5z)KLsPi3dqCH zq+n<+)2a$Afvr|B97(#s5f6-oU6qYHP<2rWEKfC)aEc=?j9nPwEyIiT4XCI%BScNpoU1Cro6M@BSt>YU4@z^JQPbj- zbMl0tf(CkBNTVH0run?8E#6lyouay;Bf8|_ud%WyA2Dkqc}nAEGkyiO!|#6>OX~jC z_3u?iQ>Xm%XNGGb_3~zzqyj(lHYRC##{sV_zNQl$KP40jQHRR#WeJ!akxfaL;HU(y z@6A7KA;pjflPx?{&_wwQ<6?f(Uld(h*XSf+Ct`QR3EDfau;y#nNiKfJ`Ny24=O+_9 z{chAh!5R0T(`<1ayxDvCtBZ?9Rn)QBoddzqchGPN4C8rB2tQ(*#m6zlySN7XwxM)X zNo%g}Q*?B_&%_K;!PvNxj9-D>BYn6zcIb@VGE=-?gP+zjpQ4x$*@_cm*TL-MtWeV+ z%v$Vh+2e#jDJ4Yc3NPgE9Uhr~V;6)j#bgMC+5!L2yYdX5ef->+k9d_?db{`}fWW+F zU&GKd9pW?cv0e8pA%20doi=OgaTV=dLOHx7cgAQlYDkLWaAUksGbO`Z7+>qo}~5K=?ZI!b@vaF5}r7- zyP2aiwSn}KbwGhrQ0A?W4L_Jwg?C#vAElLzpK~}}&ny0d@_GVhUqVEfXX9}XI8%B; z;BYTG$dM}6WS8urD4fqn$733@mNss6jB7yHY*76e*L=X6apM|Dgg^tZhpge9{Ojy9 z{Sl&x=vUbHU+7KFQEas^U*jQ8^rj_XAzI=0y_Nmx3ChT&K?_-b!N10g5+C9TqMGZ@!a>mh#`}nJM>Cu2v@32F*rQ(x05Xb64 zV-ML!u$4W31M7A@mi~3fnSOQSZ->>TC+02Mt+0csMl0*2TCklB$VOH11pW{4 zD1)V+^h4n@OYlO&;Z!-dk{(LVtA%;(o#!>jYgG>s%eL0iXx~jJsrfL3rwo;cc52kP zRnvwZId>`-FV`PUvUKk4gU&nzX&+gTEm1bNsCdaXc zvaOny-3X43Fs?Jn;>*U?jaR1`9KIVP?p(?ulraQZc;T0UKos^SChGJoJYVu1%?E0v zDGNOfZKPrPKtyFYEU~bZZ~rB{4X2ko>_VJlJw3rw-!>TIT6R!3;POq5yNZdnfu$Ao j!CVlN4fQVi0D=DiS&&%ubg+{I00000NkvXXu0mjf8bDG2 literal 0 HcmV?d00001 diff --git a/web/public/robots.txt b/web/public/robots.txt new file mode 100644 index 00000000..eb053628 --- /dev/null +++ b/web/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 00000000..97fb5e02 --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,19 @@ +import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' +import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' + +import FatalErrorPage from 'src/pages/FatalErrorPage' +import Routes from 'src/Routes' + +import './index.css' + +const App = () => ( + + + + + + + +) + +export default App diff --git a/web/src/Routes.tsx b/web/src/Routes.tsx new file mode 100644 index 00000000..2c8f02ab --- /dev/null +++ b/web/src/Routes.tsx @@ -0,0 +1,20 @@ +// In this file, all Page components from 'src/pages` are auto-imported. Nested +// directories are supported, and should be uppercase. Each subdirectory will be +// prepended onto the component name. +// +// Examples: +// +// 'src/pages/HomePage/HomePage.js' -> HomePage +// 'src/pages/Admin/BooksPage/BooksPage.js' -> AdminBooksPage + +import { Router, Route } from '@redwoodjs/router' + +const Routes = () => { + return ( + + + + ) +} + +export default Routes diff --git a/web/src/components/.keep b/web/src/components/.keep new file mode 100644 index 00000000..e69de29b diff --git a/web/src/entry.client.tsx b/web/src/entry.client.tsx new file mode 100644 index 00000000..d55036f3 --- /dev/null +++ b/web/src/entry.client.tsx @@ -0,0 +1,23 @@ +import { hydrateRoot, createRoot } from 'react-dom/client' + +import App from './App' +/** + * When `#redwood-app` isn't empty then it's very likely that you're using + * prerendering. So React attaches event listeners to the existing markup + * rather than replacing it. + * https://reactjs.org/docs/react-dom-client.html#hydrateroot + */ +const redwoodAppElement = document.getElementById('redwood-app') + +if (!redwoodAppElement) { + throw new Error( + "Could not find an element with ID 'redwood-app'. Please ensure it exists in your 'web/src/index.html' file." + ) +} + +if (redwoodAppElement.children?.length > 0) { + hydrateRoot(redwoodAppElement, ) +} else { + const root = createRoot(redwoodAppElement) + root.render() +} diff --git a/web/src/index.css b/web/src/index.css new file mode 100644 index 00000000..e69de29b diff --git a/web/src/index.html b/web/src/index.html new file mode 100644 index 00000000..e240b8eb --- /dev/null +++ b/web/src/index.html @@ -0,0 +1,15 @@ + + + + + + + + + + + +
+ + + diff --git a/web/src/layouts/.keep b/web/src/layouts/.keep new file mode 100644 index 00000000..e69de29b diff --git a/web/src/pages/FatalErrorPage/FatalErrorPage.tsx b/web/src/pages/FatalErrorPage/FatalErrorPage.tsx new file mode 100644 index 00000000..b2bb436f --- /dev/null +++ b/web/src/pages/FatalErrorPage/FatalErrorPage.tsx @@ -0,0 +1,57 @@ +// This page will be rendered when an error makes it all the way to the top of the +// application without being handled by a Javascript catch statement or React error +// boundary. +// +// You can modify this page as you wish, but it is important to keep things simple to +// avoid the possibility that it will cause its own error. If it does, Redwood will +// still render a generic error page, but your users will prefer something a bit more +// thoughtful :) + +// This import will be automatically removed when building for production +import { DevFatalErrorPage } from '@redwoodjs/web/dist/components/DevFatalErrorPage' + +export default DevFatalErrorPage || + (() => ( +
+ + +`,l=` + +`,c=` +