Giter VIP home page Giter VIP logo

awesome-links's Introduction

Prisma

Prisma

Discord

Quickstart   •   Website   •   Docs   •   Examples   •   Blog   •   Discord   •   Twitter

What is Prisma?

Prisma is a next-generation ORM that consists of these tools:

  • Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
  • Prisma Migrate: Declarative data modeling & migration system
  • Prisma Studio: GUI to view and edit data in your database

Prisma Client can be used in any Node.js or TypeScript backend application (including serverless applications and microservices). This can be a REST API, a GraphQL API, a gRPC API, or anything else that needs a database.

The Prisma ORM can also further be extended with these Prisma products:

Getting started

The fastest way to get started with Prisma is by following the Quickstart (5 min).

The Quickstart is based on a preconfigured SQLite database. You can also get started with your own database (PostgreSQL and MySQL) by following one of these guides:

How Prisma works

This section provides a high-level overview of how Prisma works and its most important technical components. For a more thorough introduction, visit the Prisma documentation.

The Prisma schema

Every project that uses a tool from the Prisma toolkit starts with a Prisma schema file. The Prisma schema allows developers to define their application models in an intuitive data modeling language. It also contains the connection to a database and defines a generator:

// Data source
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

// Generator
generator client {
  provider = "prisma-client-js"
}

// Data model
model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields:  [authorId], references: [id])
  authorId  Int?
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

In this schema, you configure three things:

  • Data source: Specifies your database connection (via an environment variable)
  • Generator: Indicates that you want to generate Prisma Client
  • Data model: Defines your application models

The Prisma data model

On this page, the focus is on the data model. You can learn more about Data sources and Generators on the respective docs pages.

Functions of Prisma models

The data model is a collection of models. A model has two major functions:

  • Represent a table in the underlying database
  • Provide the foundation for the queries in the Prisma Client API

Getting a data model

There are two major workflows for "getting" a data model into your Prisma schema:

  • Generate the data model from introspecting a database
  • Manually writing the data model and mapping it to the database with Prisma Migrate

Once the data model is defined, you can generate Prisma Client which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields).


Accessing your database with Prisma Client

Generating Prisma Client

The first step when using Prisma Client is installing its npm package:

npm install @prisma/client

Note that the installation of this package invokes the prisma generate command which reads your Prisma schema and generates the Prisma Client code. The code will be located in node_modules/.prisma/client, which is exported by node_modules/@prisma/client/index.d.ts.

After you change your data model, you'll need to manually re-generate Prisma Client to ensure the code inside node_modules/.prisma/client gets updated:

npx prisma generate

Refer to the documentation for more information about "generating the Prisma client".

Using Prisma Client to send queries to your database

Once the Prisma Client is generated, you can import it in your code and send queries to your database. This is what the setup code looks like.

Import and instantiate Prisma Client

You can import and instantiate Prisma Client as follows:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

or

const { PrismaClient } = require('@prisma/client')

const prisma = new PrismaClient()

Now you can start sending queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return plain old JavaScript objects.

Learn more about the available operations in the Prisma Client docs or watch this demo video (2 min).

Retrieve all User records from the database
// Run inside `async` function
const allUsers = await prisma.user.findMany()
Include the posts relation on each returned User object
// Run inside `async` function
const allUsers = await prisma.user.findMany({
  include: { posts: true },
})
Filter all Post records that contain "prisma"
// Run inside `async` function
const filteredPosts = await prisma.post.findMany({
  where: {
    OR: [{ title: { contains: 'prisma' } }, { content: { contains: 'prisma' } }],
  },
})
Create a new User and a new Post record in the same query
// Run inside `async` function
const user = await prisma.user.create({
  data: {
    name: 'Alice',
    email: '[email protected]',
    posts: {
      create: { title: 'Join us for Prisma Day 2021' },
    },
  },
})
Update an existing Post record
// Run inside `async` function
const post = await prisma.post.update({
  where: { id: 42 },
  data: { published: true },
})

Usage with TypeScript

Note that when using TypeScript, the result of this query will be statically typed so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the Advanced usage of generated types page in the docs.

Community

Prisma has a large and supportive community of enthusiastic application developers. You can join us on Discord and here on GitHub.

Security

If you have a security issue to report, please contact us at [email protected].

Support

Ask a question about Prisma

You can ask questions and initiate discussions about Prisma-related topics in the prisma repository on GitHub.

👉 Ask a question

Create a bug report for Prisma

If you see an error message or run into an issue, please make sure to create a bug report! You can find best practices for creating bug reports (like including additional debugging output) in the docs.

👉 Create bug report

Submit a feature request

If Prisma currently doesn't have a certain feature, be sure to check out the roadmap to see if this is already planned for the future.

If the feature on the roadmap is linked to a GitHub issue, please make sure to leave a 👍 reaction on the issue and ideally a comment with your thoughts about the feature!

👉 Submit feature request

Contributing

Refer to our contribution guidelines and Code of Conduct for contributors.

Tests Status

  • Prisma Tests Status:
    Prisma Tests Status
  • Ecosystem Tests Status:
    Ecosystem Tests Status

awesome-links's People

Contributors

m-abdelwahab avatar mjy9088 avatar ruheni avatar sonylomo avatar tericcabrel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

awesome-links's Issues

Runtime error on part-3 branch: Cannot read properties of undefined (reading 'Symbol(Pothos.contextCache)')

Full error:

- event compiled successfully in 118 ms (91 modules)
- error Error [TypeError]: Cannot read properties of undefined (reading 'Symbol(Pothos.contextCache)')
    at file:///Users/bee/projects/biowerks/software/awesome-links/node_modules/@pothos/core/esm/utils/context-cache.js:10:33
    at SchemaBuilder.prismaObject (file:///Users/bee/projects/biowerks/software/awesome-links/node_modules/@pothos/plugin-prisma/esm/schema-builder.js:18:22)
    at eval (webpack-internal:///(api)/./graphql/types/Link.ts:8:47) {
  digest: undefined

Node version: 16.15.1

Repro steps:

git checkout part-3
rm -Rf node_modules
rm -f package-lock.json
npm install 
npx prisma generate
npm run dev
`

When the browser tries to fetch localhost:3000 the error above occurs.


Incorrect import in part-1

Hi, I found that if I import 'data' as in the example, I can't find it. I need to change it to import { links as data } from "../data/links";.

image

image

GraphQL Queries fail after any changes

I completed the first 4 blog posts and thought I was understanding everything but then I tried to make an extremely small modification and everything stopped working. I changed the Link object to another name in both Prisma + Nexus and did a prisma db push and confirmed the DB was updated. Now I see that Nexus updated my queries and all the names look right, but none of my queries work. They all say "GRAPHQL_VALIDATION_FAILED".

Any advice appreciated. Trying to read through the Nexus documentation and see if I'm misunderstanding something.

Part 3? :)

Hey @m-abdelwahab, love the first two blog posts for this! Are you still planning to write a post for part 3? I noticed the part-3 branch hasn't been updated in a couple of months.

Typescript intellense not working

Hi, the awesome-links example doesn't trigger autocomplete intellisense in the IDE when accesing the prisma client in ctx, but this other example does.

Why is that? How can I make the intellisense work with awesome-links. I can't tell why it is not working.

Importing the Context type from the context file and manually assigning it to the ctx variable helps intellense figure out the prisma object is in ctx, but it doesn't generate suggestions beyond that.

Property 'connectionField' does not exist on type 'ObjectDefinitionBlock<"Query">'

Hi, I just cloned the repo and made a fresh installation of node_modules; but Typescript throwing the following error at graphql/types/Links.ts,

Property 'connectionField' does not exist on type 'ObjectDefinitionBlock<"Query">'

Any solution how to fix it other than downgrading packages? I didn't upgrade any version number form package.json, just a fresh "yarn install"

Can't query from Apollo Studio after Part 3

Hi team,

I was following the tutorial and after part 3 (Adding authentication with Auth0). I am unable to query the Graphql with Apollo Studio anymore.

I believe it must because I am unable to pass token to query to Apollo Studio so it query it as anonymous user. Do you guys have any tip how to use Apollo Studio after part 3?

Thank you very much.

Best regards,

Hoang Phi

ReferenceError: prisma is not defined

My app works fine locally and is able to pull data through the data proxy, but when I deploy I get this error.

[31mERR�[0m ReferenceError: prisma is not defined
    at resolve (/var/task/.next/server/pages/api/graphql.js:154:68)
    at file:///var/task/node_modules/@pothos/plugin-prisma/esm/field-builder.js:72:37
    at resolvePrismaCursorConnection (file:///var/task/node_modules/@pothos/plugin-prisma/esm/util/cursors.js:234:27)
    at resolve (file:///var/task/node_modules/@pothos/plugin-prisma/esm/field-builder.js:54:51)
    at executeField (file:///var/task/node_modules/@graphql-tools/executor/esm/execution/execute.js:294:24)
    at executeFields (file:///var/task/node_modules/@graphql-tools/executor/esm/execution/execute.js:241:28)
    at executeOperation (file:///var/task/node_modules/@graphql-tools/executor/esm/execution/execute.js:205:18)
    at file:///var/task/node_modules/@graphql-tools/executor/esm/execution/execute.js:62:37
    at new ValueOrPromise (/var/task/node_modules/value-or-promise/build/main/ValueOrPromise.js:14:21)
    at executeImpl (file:///var/task/node_modules/@graphql-tools/executor/esm/execution/execute.js:62:12) {
  path: [ 'links' ],
  locations: [ { line: 2, column: 3 } ],
  extensions: [Object: null prototype] {}
}

I have "vercel-build": "npx prisma generate --data-proxy && next build", in the scripts in package.json. And I can see prisma is getting generated in the deployment logs on Vercel:

Running build in Cleveland, USA (East) – cle1
--
19:52:47.943 | Cloning github.com/chriscreber/awesome-links-done (Branch: main, Commit: 12a8d69)
19:52:48.254 | Cloning completed: 310.432ms
19:52:51.502 | Restored build cache
19:52:51.533 | Running "vercel build"
19:52:52.046 | Vercel CLI 29.3.6
19:52:52.305 | Installing dependencies...
19:52:52.592 | yarn install v1.22.17
19:52:52.622 | info No lockfile found.
19:52:52.627 | [1/4] Resolving packages...
19:52:57.424 | warning aws-sdk > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
19:52:57.425 | warning aws-sdk > url > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
19:53:03.700 | [2/4] Fetching packages...
19:53:18.994 | [3/4] Linking dependencies...
19:53:18.997 | warning "graphql-yoga > @envelop/[email protected]" has incorrect peer dependency "@envelop/core@^3.0.6".
19:53:18.998 | warning "graphql-yoga > @envelop/[email protected]" has incorrect peer dependency "@envelop/core@^3.0.6".
19:53:18.998 | warning "react-hot-toast > [email protected]" has unmet peer dependency "csstype@^3.0.10".
19:53:31.896 | [4/4] Building fresh packages...
19:53:32.929 | success Saved lockfile.
19:53:32.932 | $ npx prisma generate --data-proxy
19:53:33.755 | Prisma schema loaded from prisma/schema.prisma
19:53:34.393 |  
19:53:34.394 | ✔ Generated Prisma Client (4.15.0 \| dataproxy) to ./node_modules/@prisma/client in 171ms
19:53:34.394 |  
19:53:34.394 | ✔ Generated Pothos integration to ./node_modules/@pothos/plugin-prisma/generated.ts in 18ms
19:53:34.394 | You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
19:53:34.394 | ```
19:53:34.394 | import { PrismaClient } from '@prisma/client'
19:53:34.395 | const prisma = new PrismaClient()
19:53:34.395 | ```
19:53:34.395 |  
19:53:34.395 | To use Prisma Client in edge runtimes like Cloudflare Workers or Vercel Edge Functions, import it like this:
19:53:34.395 | ```
19:53:34.396 | import { PrismaClient } from '@prisma/client/edge'
19:53:34.396 | ```
19:53:34.396 |  
19:53:34.397 | You will need a Prisma Data Proxy connection string. See documentation: https://pris.ly/d/data-proxy
19:53:34.397 |  
19:53:34.457 | Done in 41.87s.
19:53:34.498 | Detected Next.js version: 13.4.4
19:53:34.499 | Running "yarn run build"
19:53:34.700 | yarn run v1.22.17
19:53:34.732 | $ next build
19:53:35.247 | - info Linting and checking validity of types...
19:53:45.170 | - info Creating an optimized production build...
19:53:54.943 | - info Compiled successfully
19:53:54.950 | - info Collecting page data...
19:53:55.485 | in prisma file
19:53:55.485 | production
19:53:55.485 | 1
19:53:55.485 | 2
19:53:55.490 | 3
19:53:55.490 | 4
19:54:07.122 | - info Generating static pages (0/5)
19:54:07.194 | - info Generating static pages (1/5)
19:54:07.206 | - info Generating static pages (2/5)
19:54:07.207 | in index file
19:54:07.207 | new changes
19:54:07.207 | production
19:54:07.208 | true
19:54:07.208 | user: undefined
19:54:07.209 |  
19:54:07.216 | - info Generating static pages (3/5)
19:54:07.231 | - info Generating static pages (5/5)
19:54:07.428 | - info Finalizing page optimization...
19:54:07.431 |  
19:54:07.443 | Route (pages)                              Size     First Load JS
19:54:07.443 | ┌ ○ /                                      3.84 kB         134 kB
19:54:07.443 | ├   /_app                                  0 B             122 kB
19:54:07.443 | ├ ○ /404                                   182 B           122 kB
19:54:07.443 | ├ ○ /about                                 270 B           122 kB
19:54:07.443 | ├ λ /admin                                 13.8 kB         144 kB
19:54:07.443 | ├ λ /api/auth/[...auth0]                   0 B             122 kB
19:54:07.443 | ├ λ /api/auth/hook                         0 B             122 kB
19:54:07.443 | ├ λ /api/graphql                           0 B             122 kB
19:54:07.443 | ├ λ /api/upload-image                      0 B             122 kB
19:54:07.443 | ├ ○ /favorites                             3.5 kB          133 kB
19:54:07.443 | └ λ /link/[id]                             5.87 kB         136 kB
19:54:07.443 | + First Load JS shared by all              127 kB
19:54:07.443 | ├ chunks/framework-cda2f1305c3d9424.js   45.2 kB
19:54:07.444 | ├ chunks/main-6f0913649682f6ca.js        26.8 kB
19:54:07.445 | ├ chunks/pages/_app-080515f3b3b51fac.js  48.7 kB
19:54:07.445 | ├ chunks/webpack-87b3a303122f2f0d.js     995 B
19:54:07.445 | └ css/eea48206b604b5a0.css               4.92 kB
19:54:07.445 |  
19:54:07.445 | λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
19:54:07.445 | ○  (Static)  automatically rendered as static HTML (uses no initial props)
19:54:07.445 |  
19:54:08.129 | Done in 33.43s.
19:54:11.246 | Traced Next.js server files in: 3.080s
19:54:14.128 | Created all serverless functions in: 2.880s
19:54:14.134 | Collected static files (public/, static/, .next/static): 4.086ms
19:54:15.663 | Build Completed in /vercel/output [1m]
19:54:16.246 | Deploying outputs...
19:54:24.378 | Deployment completed
19:54:29.654 | Uploading build cache [115.83 MB]...
19:54:32.320 | Build cache uploaded: 2.666s

Please help.

Are the old branches available?

Hi, I'm trying to follow along, and am stuck at the last step of the 2nd instalment.

I can see there is an instruction to update the resolver, but I can't see how or where to do that. The part 2 repo no longer has a resolvers file in the graphql folder. Where did that go?

I have an error message with the form of the index.tsx file, that says: Property 'links' does not exist on type 'unknown'. I don't seem to be defining links in that file. How did you do that?

Thank you?

Nexus and ApolloServer types discrepancy

When passing a Nexus-generated schema to ApolloServer like this:

const apolloServer = new ApolloServer({
   schema,
   resolvers,
   context: createContext,
});

the editor starts screaming at me saying Type 'NexusGraphQLSchema' is missing the following properties from type 'GraphQLSchema': _queryType, _mutationType, _subscriptionType, _directives, and 3 more..

Here is my graphql.ts file:

import { ApolloServer } from "apollo-server-micro";
import { schema } from "../../graphql/schema";
import { resolvers } from "../../graphql/resolvers";
import { createContext } from "../../graphql/context";
import Cors from "micro-cors";

const cors = Cors();

const apolloServer = new ApolloServer({
   schema,
   resolvers,
   context: createContext,
});

const startServer = apolloServer.start();

const handler = async (req, res) => {
   if (req.method === "OPTIONS") {
      res.end();
      return false;
   }

   await startServer;

   await apolloServer.createHandler({
      path: "/api/graphql",
   })(req, res);
};

export default cors(handler);

export const config = {
   api: {
      bodyParser: false,
   },
};

And my schema.ts file:

import { makeSchema } from "nexus";
import { join } from "path";
import * as types from "./types";

export const schema = makeSchema({
   types,
   outputs: {
      typegen: join(
         process.cwd(),
         "node_modules",
         "@types",
         "nexus-typegen",
         "index.d.ts"
      ),
      schema: join(process.cwd(), "graphql", "schema.graphql"),
   },
   contextType: {
      export: "Context",
      module: join(process.cwd(), "graphql", "context.ts"),
   },
});

So far I haven't been able to solve the issue nor find any reference of it online, apart from a comment under your Building a GraphQL schema using Nexus, Prisma and Nextjs video mentioning the same error message.

How to manipulate/use DateTime using Nexus ?

Hi, first and foremost "Thank you"

Thanks to your tutorial i have been able to start a personal project using :

  • NextJS
  • Chakra UI
  • Prisma
  • Nexus
  • Apollo
  • Sqlite

All of which are new to me.

I'm a beginner in the database/ORM/GraphQL world


I have been stuck a bit on an issue lately

"How to use DateTime inside Nexus ?"

To explain a bit, following/adapting your tutorial i did this

// graphql/types/recipe.ts
export const Recipe = objectType({
    name: 'Recipe',
    definition(t) {
        t.string('id')
        t.string('name')
        t.string('description')
        t.string('url')
        t.string('category')
        t.string('createdAt')  //  Not the good Type (should be a "DateTime")
        t.string('updatedAt')  //  Not the good Type (should be a "DateTime")
    },
})

But i had seated "this" inside schema.prisma

// schema.prisma
model Recipe {
  id          String   @id @unique
  name        String
  description String
  url         String
  category    String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

Finally i had a Typescript error on a query "resolver". I took a bit of time to found that error.

Copy past are evil


From my understanding , nexus doesn't support "DateTime" natively

In order to implement DateTime type you need to setup some complexe "mapping" inside the makeSchema method (could you point me on the documentation ?)

Or use nexus-prisma in order to make prisma and nexus communicate about the types.

Is there another way? I am missing something else ?

If you're close to the team developing nexus-prisma tell them i'm waiting for this plugin 😁


Thanks you again

You're helping me becoming a better developer

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.