{"id":15162293,"url":"https://github.com/andrei-r1/twitter-clone-backend-v2","last_synced_at":"2026-01-21T12:02:33.438Z","repository":{"id":125327402,"uuid":"574636275","full_name":"Andrei-R1/twitter-clone-backend-v2","owner":"Andrei-R1","description":"V2 of the twitter clone, now with GraphQL and TS","archived":false,"fork":false,"pushed_at":"2022-12-08T22:55:34.000Z","size":87,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-08T03:25:04.514Z","etag":null,"topics":["apollo","authentication","graphql","graphql-api"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Andrei-R1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-12-05T18:41:11.000Z","updated_at":"2022-12-13T02:24:45.000Z","dependencies_parsed_at":null,"dependency_job_id":"77abc4f7-bd09-4443-a3c9-c30ad2277bb9","html_url":"https://github.com/Andrei-R1/twitter-clone-backend-v2","commit_stats":{"total_commits":14,"total_committers":1,"mean_commits":14.0,"dds":0.0,"last_synced_commit":"c4bab83e239fc372d6b295b2b6bede356d6d904b"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":"Andrei-R1/GraphQL-TS-Boilerplate","purl":"pkg:github/Andrei-R1/twitter-clone-backend-v2","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Andrei-R1%2Ftwitter-clone-backend-v2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Andrei-R1%2Ftwitter-clone-backend-v2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Andrei-R1%2Ftwitter-clone-backend-v2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Andrei-R1%2Ftwitter-clone-backend-v2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Andrei-R1","download_url":"https://codeload.github.com/Andrei-R1/twitter-clone-backend-v2/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Andrei-R1%2Ftwitter-clone-backend-v2/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28632781,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-21T04:47:28.174Z","status":"ssl_error","status_checked_at":"2026-01-21T04:47:22.943Z","response_time":86,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apollo","authentication","graphql","graphql-api"],"created_at":"2024-09-27T01:22:36.523Z","updated_at":"2026-01-21T12:02:33.419Z","avatar_url":"https://github.com/Andrei-R1.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# GraphQL Server with Authentication \u0026 Permissions\n\nThis example shows how to implement a **GraphQL server with TypeScript** with the following stack:\n\n- [**Apollo Server**](https://github.com/apollographql/apollo-server): HTTP server for GraphQL APIs\n- [**GraphQL Nexus**](https://nexusjs.org/docs/): GraphQL schema definition and resolver implementation\n- [**GraphQL Shield**](https://github.com/maticzav/graphql-shield): Authorization/permission layer for GraphQL schemas\n- [**Prisma Client**](https://www.prisma.io/docs/concepts/components/prisma-client): Databases access (ORM)\n- [**Prisma Migrate**](https://www.prisma.io/docs/concepts/components/prisma-migrate): Database migrations\n- [**SQLite**](https://www.sqlite.org/index.html): Local, file-based SQL database\n\n## Contents\n\n- [Getting Started](#getting-started)\n- [Using the GraphQL API](#using-the-graphql-api)\n- [Evolving the app](#evolving-the-app)\n- [Switch to another database (e.g. PostgreSQL, MySQL, SQL Server)](#switch-to-another-database-eg-postgresql-mysql-sql-server)\n- [Next steps](#next-steps)\n\n## Getting started\n\n### 1. Download example and install dependencies\n\nDownload this example:\n\n```\ngit clone https://github.com/Andrei-R1/GraphQL-TS-Boilerplate\n```\n\nInstall npm dependencies:\n\n```\ncd graphql-auth\nnpm install\n```\n\n### 2. Create and seed the database\n\nRun the following command to create your SQLite database file. This also creates the `User` and `Post` tables that are defined in [`prisma/schema.prisma`](./prisma/schema.prisma):\n\n```\nnpx prisma migrate dev --name init\n```\n\nWhen `npx prisma migrate dev` is executed against a newly created database, seeding is also triggered. The seed file in [`prisma/seed.ts`](./prisma/seed.ts) will be executed and your database will be populated with the sample data.\n\n### 3. Start the GraphQL server\n\nLaunch your GraphQL server with this command:\n\n```\nnpm run dev\n```\n\nNavigate to [http://localhost:4000](http://localhost:4000) in your browser to explore the API of your GraphQL server in a [GraphQL Playground](https://github.com/prisma/graphql-playground).\n\n## Using the GraphQL API\n\nThe schema that specifies the API operations of your GraphQL server is defined in [`./schema.graphql`](./schema.graphql). Below are a number of operations that you can send to the API using the GraphQL Playground.\n\nFeel free to adjust any operation by adding or removing fields. The GraphQL Playground helps you with its auto-completion and query validation features.\n\n### Retrieve all published posts and their authors\n\n```graphql\nquery {\n  feed {\n    id\n    title\n    content\n    published\n    author {\n      id\n      name\n      email\n    }\n  }\n}\n```\n\n\u003cdetails\u003e\u003csummary\u003e\u003cstrong\u003eSee more API operations\u003c/strong\u003e\u003c/summary\u003e\n\n### Register a new user\n\nYou can send the following mutation in the Playground to sign up a new user and retrieve an authentication token for them:\n\n```graphql\nmutation {\n  signup(name: \"Sarah\", email: \"sarah@prisma.io\", password: \"HelloWorld42\") {\n    token\n  }\n}\n```\n\n### Log in an existing user\n\nThis mutation will log in an existing user by requesting a new authentication token for them.\n\n```graphql\nmutation {\n  login(email: \"sarah@prisma.io\", password: \"HelloWorld42\") {\n    token\n  }\n}\n```\n\nIf you seeded the database with sample data in step 2. of this README, you can use the following `email` and `password` combinations (from [`prisma/seed.ts`](./prisma/seed.ts)) for the `login` mutation as well:\n\n| Email                 | Password           |\n| :-------------------- | :----------------- |\n| `alice@prisma.io`   | `myPassword42`   |\n| `nilu@prisma.io`    | `random42`       |\n| `mahmoud@prisma.io` | `iLikeTurtles42` |\n\n### Check whether a user is currently logged in with the `me` query\n\nFor this query, you need to make sure a valid authentication token is sent along with the `Bearer`-prefix in the `Authorization` header of the request:\n\n```json\n{\n  \"Authorization\": \"Bearer __YOUR_TOKEN__\"\n}\n```\n\nWith a real token, this looks similar to this:\n\n```json\n{\n  \"Authorization\": \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjanAydHJyczFmczE1MGEwM3kxaWl6c285IiwiaWF0IjoxNTQzNTA5NjY1fQ.Vx6ad6DuXA0FSQVyaIngOHYVzjKwbwq45flQslnqX04\"\n}\n```\n\nInside the Playground, you can set HTTP headers in the bottom-left corner:\n\n![](https://imgur.com/ToRcCTj.png)\n\nOnce you've set the header, you can send the following query to check whether the token is valid:\n\n```graphql\n{\n  me {\n    id\n    name\n    email\n  }\n}\n```\n\n### Create a new draft\n\nYou need to be logged in for this query to work, i.e. an authentication token that was retrieved through a `signup` or `login` mutation needs to be added to the `Authorization` header in the GraphQL Playground.\n\n```graphql\nmutation {\n  createDraft(\n    data: {\n      title: \"Join the Prisma Slack\"\n      content: \"https://slack.prisma.io\"\n    }\n  ) {\n    id\n    published\n  }\n}\n```\n\n### Publish an existing post\n\nYou need to be logged in for this query to work, i.e. an authentication token that was retrieved through a `signup` or `login` mutation needs to be added to the `Authorization` header in the GraphQL Playground. The authentication token must belong to the user who created the post.\n\n```graphql\nmutation {\n  togglePublishPost(id: __POST_ID__) {\n    id\n    published\n  }\n}\n```\n\nNote that you need to replace the `__POST_ID__` placeholder with an actual `id` from a `Post` record in the database, e.g.`5`:\n\n```graphql\nmutation {\n  togglePublishPost(id: 5) {\n    id\n    published\n  }\n}\n```\n\n### Search for posts with a specific title or content\n\n```graphql\n{\n  feed(\n    searchString: \"prisma\"\n  ) {\n    id\n    title\n    content\n    published\n  }\n}\n```\n\n### Retrieve a single post\n\nYou need to be logged in for this query to work, i.e. an authentication token that was retrieved through a `signup` or `login` mutation needs to be added to the `Authorization` header in the GraphQL Playground.\n\n```graphql\n{\n  postById(id: __POST_ID__ ) {\n    id\n    title\n    content\n    published\n  }\n}\n```\n\nNote that you need to replace the `__POST_ID__` placeholder with an actual `id` from a `Post` record in the database, e.g.`5`:\n\n```graphql\n{\n  postById(id: 5 ) {\n    id\n    title\n    content\n    published\n  }\n}\n```\n\n### Delete a post\n\nYou need to be logged in for this query to work, i.e. an authentication token that was retrieved through a `signup` or `login` mutation needs to be added to the `Authorization` header in the GraphQL Playground. The authentication token must belong to the user who created the post.\n\n```graphql\nmutation {\n  deletePost(id: __POST_ID__) {\n    id\n  }\n}\n```\n\nNote that you need to replace the `__POST_ID__` placeholder with an actual `id` from a `Post` record in the database, e.g.`5`:\n\n```graphql\nmutation {\n  deletePost(id: 5) {\n    id\n  }\n}\n```\n\n### Retrieve the drafts of a user\n\nYou need to be logged in for this query to work, i.e. an authentication token that was retrieved through a `signup` or `login` mutation needs to be added to the `Authorization` header in the GraphQL Playground.\n\n```graphql\n{\n  draftsByUser(\n    userUniqueInput: {\n      email: \"mahmoud@prisma.io\"\n    }\n  ) {\n    id\n    title\n    content\n    published\n    author {\n      id\n      name\n      email\n    }\n  }\n}\n```\n\n\u003c/details\u003e\n\n### Authenticating GraphQL requests\n\nIn this example, you authenticate your GraphQL requests using the `Authorization` header field of the HTTP requests which are sent from clients to your GraphQL server. The required authentication token is returned by successful `signup` and `login` mutations.\n\nUsing the GraphQL Playground, the `Authorization` header can be configured in the **HTTP HEADERS** tab in the bottom-left corner of the GraphQL Playground. The values for the HTTP headers are defined in JSON format. Note that the authentication token needs to be sent with the `Bearer `-prefix:\n\n```json\n{\n  \"Authorization\": \"Bearer __YOUR_TOKEN__\"\n}\n```\n\nWith a \"real\" authentication token, it looks similar to this:\n\n```json\n{\n  \"Authorization\": \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjanAydHJyczFmczE1MGEwM3kxaWl6c285IiwiaWF0IjoxNTQzNTA5NjY1fQ.Vx6ad6DuXA0FSQVyaIngOHYVzjKwbwq45flQslnqX04\"\n}\n```\n\nAs mentioned before, you can set HTTP headers in the bottom-left corner of the GraphQL Playground:\n\n![](https://imgur.com/ToRcCTj.png)\n\n### Authorization rules\n\nThe following [authorization rules](./src/permissions/index.ts) are defined for the GraphQL API via GraphQL Shield:\n\n| Operation name             | Operation type | Rule                    | Description                                                                              |\n| :------------------------- | :------------- | :---------------------- | :--------------------------------------------------------------------------------------- |\n| `me`                     | Query          | `isAuthenticatedUser` | Requires a user to be authenticated                                                      |\n| `draftsByUser`           | Query          | `isAuthenticatedUser` | Requires a user to be authenticated                                                      |\n| `postById`               | Query          | `isAuthenticatedUser` | Requires a user to be authenticated                                                      |\n| `createDraft`            | Mutation       | `isAuthenticatedUser` | Requires a user to be authenticated                                                      |\n| `deletePost`             | Mutation       | `isPostOwner`         | Requires the authenticated user to be the author of the post to be deleted               |\n| `incrementPostViewCount` | Mutation       | `isAuthenticatedUser` | Requires a user to be authenticated                                                      |\n| `togglePublishPost`      | Mutation       | `isPostOwner`         | Requires the authenticated user to be the author of the post to be published/unpublished |\n\nThe `isAuthenticatedUser` rule requires you to send a valid authentication token. The `isPostOwner` rule additionaly requires the user to whom this authentication token belongs to be the author of the post on which the operation is applied.\n\n## Evolving the app\n\nEvolving the application typically requires two steps:\n\n1. Migrate your database using Prisma Migrate\n2. Update your application code\n\nFor the following example scenario, assume you want to add a \"profile\" feature to the app where users can create a profile and write a short bio about themselves.\n\n### 1. Migrate your database using Prisma Migrate\n\nThe first step is to add a new table, e.g. called `Profile`, to the database. You can do this by adding a new model to your [Prisma schema file](./prisma/schema.prisma) file and then running a migration afterwards:\n\n```diff\n// ./prisma/schema.prisma\n\nmodel User {\n  id      Int      @default(autoincrement()) @id\n  name    String?\n  email   String   @unique\n  posts   Post[]\n+ profile Profile?\n}\n\nmodel Post {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n  title     String\n  content   String?\n  published Boolean  @default(false)\n  viewCount Int      @default(0)\n  author    User?    @relation(fields: [authorId], references: [id])\n  authorId  Int?\n}\n\n+model Profile {\n+  id     Int     @default(autoincrement()) @id\n+  bio    String?\n+  user   User    @relation(fields: [userId], references: [id])\n+  userId Int     @unique\n+}\n```\n\nOnce you've updated your data model, you can execute the changes against your database with the following command:\n\n```\nnpx prisma migrate dev --name add-profile\n```\n\nThis adds another migration to the `prisma/migrations` directory and creates the new `Profile` table in the database.\n\n### 2. Update your application code\n\nYou can now use your `PrismaClient` instance to perform operations against the new `Profile` table. Those operations can be used to implement queries and mutations in the GraphQL API.\n\n#### 2.1. Add the `Profile` type to your GraphQL schema\n\nFirst, add a new GraphQL type via Nexus' `objectType` function:\n\n```diff\n// ./src/schema.ts\n\n+const Profile = objectType({\n+  name: 'Profile',\n+  definition(t) {\n+    t.nonNull.int('id')\n+    t.string('bio')\n+    t.field('user', {\n+      type: 'User',\n+      resolve: (parent, _, context) =\u003e {\n+        return context.prisma.profile\n+          .findUnique({\n+            where: { id: parent.id || undefined },\n+          })\n+          .user()\n+      },\n+    })\n+  },\n+})\n\nconst User = objectType({\n  name: 'User',\n  definition(t) {\n    t.nonNull.int('id');\n    t.string('name');\n    t.nonNull.string('email');\n    t.nonNull.list.nonNull.field('posts', {\n      type: 'Post',\n      resolve: (parent, _, context) =\u003e {\n        return context.prisma.user\n          .findUnique({\n            where: { id: parent.id || undefined },\n          })\n          .posts();\n      },\n+    t.field('profile', {\n+      type: 'Profile',\n+      resolve: (parent, _, context) =\u003e {\n+        return context.prisma.user\n+          .findUnique({ \n+            where: { id: parent.id }, \n+          })\n+          .profile();\n+      },\n+    });\n  },\n});\n```\n\nDon't forget to include the new type in the `types` array that's passed to `makeSchema`:\n\n```diff\nexport const schema = makeSchema({\n  types: [\n    Query,\n    Mutation,\n    Post,\n    User,\n+   Profile,\n    UserUniqueInput,\n    UserCreateInput,\n    PostCreateInput,\n    PostOrderBy,\n    DateTime,\n  ],\n  // ... as before\n}\n```\n\nNote that in order to resolve any type errors, your development server needs to be running so that the Nexus types can be generated. If it's not running, you can start it with `npm run dev`.\n\n#### 2.2. Add a `createProfile` GraphQL mutation\n\n```diff\n// ./src/schema.ts\n\nconst Mutation = objectType({\n  name: 'Mutation',\n  definition(t) {\n\n    // other mutations\n\n+   t.field('addProfileForUser', {\n+     type: 'Profile',\n+     args: {\n+       userUniqueInput: nonNull(\n+         arg({\n+           type: 'UserUniqueInput',\n+         }),\n+       ),\n+       bio: stringArg()\n+     }, \n+     resolve: async (_, args, context) =\u003e {\n+       return context.prisma.profile.create({\n+         data: {\n+           bio: args.bio,\n+           user: {\n+             connect: {\n+               id: args.userUniqueInput.id || undefined,\n+               email: args.userUniqueInput.email || undefined,\n+             }\n+           }\n+         }\n+       })\n+     }\n+   })\n\n  }\n})\n```\n\nFinally, you can test the new mutation like this:\n\n```graphql\nmutation {\n  addProfileForUser(\n    userUniqueInput: {\n      email: \"mahmoud@prisma.io\"\n    }\n    bio: \"I like turtles\"\n  ) {\n    id\n    bio\n    user {\n      id\n      name\n    }\n  }\n}\n```\n\n\u003cdetails\u003e\u003csummary\u003eExpand to view more sample Prisma Client queries on \u003ccode\u003eProfile\u003c/code\u003e\u003c/summary\u003e\n\nHere are some more sample Prisma Client queries on the new `\u003ccode\u003e`Profile`\u003c/code\u003e` model:\n\n##### Create a new profile for an existing user\n\n```ts\nconst profile = await prisma.profile.create({\n  data: {\n    bio: 'Hello World',\n    user: {\n      connect: { email: 'alice@prisma.io' },\n    },\n  },\n})\n```\n\n##### Create a new user with a new profile\n\n```ts\nconst user = await prisma.user.create({\n  data: {\n    email: 'john@prisma.io',\n    name: 'John',\n    profile: {\n      create: {\n        bio: 'Hello World',\n      },\n    },\n  },\n})\n```\n\n##### Update the profile of an existing user\n\n```ts\nconst userWithUpdatedProfile = await prisma.user.update({\n  where: { email: 'alice@prisma.io' },\n  data: {\n    profile: {\n      update: {\n        bio: 'Hello Friends',\n      },\n    },\n  },\n})\n```\n\n\u003c/details\u003e\n\n## Switch to another database (e.g. PostgreSQL, MySQL, SQL Server, MongoDB)\n\nIf you want to try this example with another database than SQLite, you can adjust the the database connection in [`prisma/schema.prisma`](./prisma/schema.prisma) by reconfiguring the `datasource` block.\n\nLearn more about the different connection configurations in the [docs](https://www.prisma.io/docs/reference/database-reference/connection-urls).\n\n\u003cdetails\u003e\u003csummary\u003eExpand for an overview of example configurations with different databases\u003c/summary\u003e\n\n### PostgreSQL\n\nFor PostgreSQL, the connection URL has the following structure:\n\n```prisma\ndatasource db {\n  provider = \"postgresql\"\n  url      = \"postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA\"\n}\n```\n\nHere is an example connection string with a local PostgreSQL database:\n\n```prisma\ndatasource db {\n  provider = \"postgresql\"\n  url      = \"postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public\"\n}\n```\n\n### MySQL\n\nFor MySQL, the connection URL has the following structure:\n\n```prisma\ndatasource db {\n  provider = \"mysql\"\n  url      = \"mysql://USER:PASSWORD@HOST:PORT/DATABASE\"\n}\n```\n\nHere is an example connection string with a local MySQL database:\n\n```prisma\ndatasource db {\n  provider = \"mysql\"\n  url      = \"mysql://janedoe:mypassword@localhost:3306/notesapi\"\n}\n```\n\n### Microsoft SQL Server\n\nHere is an example connection string with a local Microsoft SQL Server database:\n\n```prisma\ndatasource db {\n  provider = \"sqlserver\"\n  url      = \"sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;\"\n}\n```\n\n### MongoDB\n\nHere is an example connection string with a local MongoDB database:\n\n```prisma\ndatasource db {\n  provider = \"mongodb\"\n  url      = \"mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin\u0026retryWrites=true\u0026w=majority\"\n}\n```\n\nBecause MongoDB is currently in [Preview](https://www.prisma.io/docs/about/releases#preview), you need to specify the `previewFeatures` on your `generator` block:\n\n```\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"mongodb\"]\n}\n```\n\n\u003c/details\u003e\n\n## Next steps\n\n- Check out the [Prisma docs](https://www.prisma.io/docs)\n- Share your feedback in the [`prisma2`](https://prisma.slack.com/messages/CKQTGR6T0/) channel on the [Prisma Slack](https://slack.prisma.io/)\n- Create issues and ask questions on [GitHub](https://github.com/prisma/prisma/)\n- Watch our biweekly \"What's new in Prisma\" livestreams on [Youtube](https://www.youtube.com/channel/UCptAHlN1gdwD89tFM3ENb6w)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrei-r1%2Ftwitter-clone-backend-v2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrei-r1%2Ftwitter-clone-backend-v2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrei-r1%2Ftwitter-clone-backend-v2/lists"}