Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add tasks related queries and mutations #23

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
18.11
v18.12.1
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib",
"cSpell.words": ["Pothos"]
}
4 changes: 3 additions & 1 deletion apps/api/.example.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
PORT=
DATABASE_URL=
AUTH0_DOMAIN=
BASE_URL=
BASE_URL=
NODE_ENV=
WEBHOOK_SECRET=
3 changes: 2 additions & 1 deletion apps/api/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ version: '3.8'

services:
database:
image: postgres:14.5-alpine
restart: always
image: postgres:15.1-alpine
ports:
- '5432:5432'
environment:
Expand Down
9 changes: 7 additions & 2 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
"dependencies": {
"@envelop/auth0": "^3.6.0",
"@escape.tech/graphql-armor": "^1.4.0",
"@faker-js/faker": "^7.6.0",
"@fastify/type-provider-typebox": "^2.3.0",
"@graphql-yoga/node": "^2.13.13",
"@mobily/ts-belt": "^3.13.1",
"@pothos/core": "^3.22.5",
"@pothos/plugin-directives": "^3.8.1",
"@pothos/plugin-prisma": "^3.35.4",
"@prisma/client": "^4.4.0",
"@pothos/plugin-prisma-utils": "^0.4.7",
"@prisma/client": "^4.6.1",
"@sinclair/typebox": "^0.24.47",
"consola": "^2.15.3",
"dotenv": "^16.0.3",
Expand All @@ -45,12 +47,15 @@
"easygraphql-tester": "^6.0.1",
"graphql-schema-linter": "^3.0.1",
"jest": "^29.1.2",
"prisma": "^4.4.0",
"prisma": "^4.6.1",
"supertest": "^6.2.4",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"tsx": "^3.10.1",
"typescript": "^4.8.4",
"wait-on": "^6.0.1"
},
"prisma": {
"seed": "ts-node ./prisma/seed.ts"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
Warnings:

- Added the required column `status` to the `tasks` table without a default value. This is not possible if the table is not empty.
- Added the required column `thumbnail_url` to the `tasks` table without a default value. This is not possible if the table is not empty.

*/
-- CreateEnum
CREATE TYPE "Status" AS ENUM ('IN_REVIEW', 'ACTIVE');

-- AlterTable
ALTER TABLE "tasks" ADD COLUMN "status" "Status" NOT NULL,
ADD COLUMN "thumbnail_url" TEXT NOT NULL;
9 changes: 9 additions & 0 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

generator client {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity", "fullTextSearch", "extendedWhereUnique", "interactiveTransactions"]
}

generator pothos {
Expand Down Expand Up @@ -44,12 +45,20 @@ model Task {
rating Int
difficulty Difficulty

status Status
thumbnail_url String

created_at DateTime @default(now())
updated_at DateTime @updatedAt

@@map("tasks")
}

enum Status {
IN_REVIEW
ACTIVE
}

enum Difficulty {
BEGINNER
INTERMEDIATE
Expand Down
51 changes: 51 additions & 0 deletions apps/api/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { PrismaClient } from '@prisma/client';
import { faker } from '@faker-js/faker';

const prisma = new PrismaClient();

faker.setLocale('pl');

const main = async () => {
await Promise.all([prisma.task.deleteMany(), prisma.user.deleteMany()]);

await prisma.user.createMany({
data: Array.from({ length: 5 }, () => {
const name = faker.name.firstName();
return {
email: faker.internet.email(name),
name,
nickname: faker.internet.userName(name),
picture: faker.image.avatar(),
user_id: faker.datatype.uuid(),
};
}),
});

const users = await prisma.user.findMany();

await prisma.task.createMany({
data: Array.from({ length: 100 }, () => ({
title: faker.random.words(3),
description: faker.lorem.paragraphs(1),
difficulty: faker.helpers.arrayElement([
'BEGINNER',
'INTERMEDIATE',
'ADVANCED',
]),
rating: faker.datatype.number({ min: 0, max: 5 }),
status: faker.helpers.arrayElement(['IN_REVIEW', 'ACTIVE']),
thumbnail_url: faker.image.imageUrl(),
user_id: faker.helpers.arrayElement(users).id,
})),
});
};

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
77 changes: 69 additions & 8 deletions apps/api/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ type AuthInfo {
sub: String
}

input CreateTasksInput {
description: String!
difficulty: Difficulty!
status: Status!
thumbnail_url: String!
title: String!
}

input CursorInput {
id: Int!
}

"""
A date string, such as 2007-12-03, compliant with the `full-date` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar.
"""
Expand All @@ -13,22 +25,71 @@ A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `dat
"""
scalar DateTime

input DeleteTasksInput {
id: Int!
}

enum Difficulty {
ADVANCED
BEGINNER
INTERMEDIATE
}

scalar File

type Mutation {
createTask(input: CreateTasksInput!): Task
deleteTask(input: DeleteTasksInput!): Task
updateTask(input: UpdateTasksInput!): Task
}

type Query {
allUsers: [User!]!
allUsers: [User!]

"""Auth0 context info"""
authInfo: AuthInfo
task(input: TaskInput!): Task
tasks(input: TasksInput): [Task!]
}

enum Status {
ACTIVE
IN_REVIEW
}

type Task {
description: String!
id: ID!
title: String!
description: String
id: ID
status: Status
title: String
user: User
}

input TaskInput {
id: Int!
}

input TasksInput {
cursor: CursorInput
status: Status

"""How many records you want?"""
take: Int = 10
}

input UpdateTasksInput {
description: String
difficulty: Difficulty
id: Int!
rating: Int
status: Status
thumbnail_url: String
title: String
}

type User {
email: String!
id: ID!
name: String!
postedTasks: [Task!]!
email: String
id: ID
name: String
postedTasks: [Task!]
}
50 changes: 18 additions & 32 deletions apps/api/src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import PluginPrisma from '@pothos/plugin-prisma';
import { client } from './prisma';
import type PrismaTypes from '@pothos/plugin-prisma/generated';

export const builder = new SchemaBuilder<{
type SchemaCustomTypes = {
Context: Context;
Scalars: {
Date: { Input: Date; Output: Date };
DateTime: { Input: Date; Output: Date };
File: { Input: File; Output: never };
};
Directives: {
rateLimit: {
Expand All @@ -19,44 +20,29 @@ export const builder = new SchemaBuilder<{
};
};
PrismaTypes: PrismaTypes;
}>({
DefaultFieldNullability: true;
DefaultInputFieldRequiredness: true;
};

export type TypesWithDefaults =
PothosSchemaTypes.ExtendDefaultTypes<SchemaCustomTypes>;

export const builder = new SchemaBuilder<SchemaCustomTypes>({
plugins: [DirectivePlugin, PluginPrisma],
prisma: {
client,
},
defaultFieldNullability: true,
defaultInputFieldRequiredness: true,
});

builder.scalarType('File', {
serialize: () => {
throw new Error('Uploads can only be used as input types');
},
});
builder.addScalarType('Date', DateResolver, {});
builder.addScalarType('DateTime', DateTimeResolver, {});

builder.prismaObject('Task', {
findUnique: (task) => ({ id: task.id }),
fields: (t) => ({
id: t.exposeID('id'),
title: t.exposeString('title'),
description: t.exposeString('description'),
}),
});

builder.prismaObject('User', {
findUnique: (user) => ({ id: user.id }),
fields: (t) => ({
id: t.exposeID('id'),
email: t.exposeString('email'),
name: t.exposeString('name'),
postedTasks: t.relation('posted_tasks'),
}),
});

builder.queryField('allUsers', (t) =>
t.prismaField({
type: ['User'],
async resolve(query, _parent, _args, _ctx, _info) {
return await client.user.findMany({
...query,
});
},
}),
);

builder.queryType({});
builder.mutationType({});
17 changes: 15 additions & 2 deletions apps/api/src/grapqhl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { EnvelopArmorPlugin } from '@escape.tech/graphql-armor';
import { pipe } from '@mobily/ts-belt';
import { lexicographicSortSchema, printSchema } from 'graphql';
import { rateLimitDirective } from 'graphql-rate-limit-directive';
import { createYoga } from 'graphql-yoga';
import { createYoga, useExtendContext } from 'graphql-yoga';

import { env } from './config';
import { client } from './prisma';
import { schema as rawSchema } from './schema';
import type { Context } from './types';

Expand All @@ -23,13 +24,25 @@ export const instance = createYoga<Context>({
schema,
maskedErrors: env.isProd,
landingPage: env.isDev,
context: (ctx) => ({
...ctx,
db: client,
}),
plugins: [
useAuth0({
domain: env.AUTH0_DOMAIN,
audience: `https://${env.BASE_URL}/graphql`,
audience: `${env.BASE_URL}/graphql`,
extendContextField: 'auth0',
preventUnauthenticatedAccess: env.isProd,
}),
useExtendContext(async (ctx: Context) => {
const user_id = ctx.auth0?.sub;
const user = user_id
? await client.user.findUnique({ where: { user_id } })
: null;

return { ...ctx, user };
}),
EnvelopArmorPlugin({
maxDepth: { n: 5 },
maxAliases: { n: 2 },
Expand Down
Loading