### Navigate and Start Development Server Source: https://github.com/getcronit/pylon/blob/main/README.md After creating the project, navigate into the project directory and start the development server. The server typically runs on http://localhost:3000. ```bash cd my-pylon npm run dev ``` -------------------------------- ### Set Up HonoJS Service Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx This TypeScript code defines a basic HonoJS service with endpoints for fetching users and blogs, creating blogs, and a placeholder route. Ensure you have Bun or Node.js installed. ```typescript import { Hono } from 'hono' const app = new Hono() const getUserById = async (id: string) => ({ id, name: 'John Doe', email: `john.doe${id}@example.com`, age: 30, posts: ['1', '2'] }) const getBlogById = async (id: string) => ({ id, title: 'Hello World', content: 'This is a blog post', authorId: '1' }) const createBlog = async (id: string, title: string, content: string, authorId: string) => ({ id, title, content, authorId }) app.get('/users', async(c) => { const id = c.req.query('id') if (!id) { c.status(400) return c.json({}) } const user = await getUserById(id) return c.json(user) }) app.get('/blog', async(c) => { const id = c.req.query('id') if (!id) { c.status(400) return c.json({}) } const blog = await getBlogById(id) return c.json(blog) }) app.post('/blogs', async(c) => { const {title, content, authorId} = await c.req.json() if (!title || !content || !authorId) { c.status(400) return c.json({}) } const blog = await createBlog('1', title, content, authorId) c.status(201) return c.json(blog) }) app.post('/post', (c) => { return c.json({message: 'a route that you want to keep'}) }) export default app ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/contributing/how-to-contribute.mdx Navigate into the cloned repository and install project dependencies using npm. ```bash cd pylon npm install ``` -------------------------------- ### Install Prisma Extended Models Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx Install the @getcronit/prisma-extended-models package using bun. ```bash bun add @getcronit/prisma-extended-models ``` -------------------------------- ### Start Development Server with Node Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx Use this command to start your development server if you are using Node.js. ```sh npm run dev ``` -------------------------------- ### Manual Deployment of Pylon Service Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/getting-started.mdx Start your Pylon service manually after building for production. Use this for environments that do not support Docker or for custom setups. ```bash node .pylon/index.js ``` ```bash bun run .pylon/index.js ``` -------------------------------- ### Install Pylon CLI Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-1.0.mdx Install the Pylon Command Line Interface globally using npm. ```bash npm install -g @getcronit/pylon-cli ``` -------------------------------- ### Run Pylon Development Server Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-1.0.mdx Start the development server for a Pylon project using bun. ```bash bun run dev ``` -------------------------------- ### Start Pylon Development Server with Custom Command Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-2.0.mdx Initiates the Pylon development server. Use the -c flag to specify a runtime-specific start command, ensuring a unified development experience across different environments. ```bash pylon dev -c 'bun run .pylon/index.js' ``` -------------------------------- ### Define a Custom Route with Pylon App Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/context-management.mdx Example of defining a simple GET route on the Pylon app instance. This demonstrates basic route handling within the Pylon framework. ```typescript app.get('/hello', (ctx, next) => { return new Response('Hello, world!') }) ``` -------------------------------- ### Initialize Local D1 Database and Run Server Source: https://github.com/getcronit/pylon/blob/main/examples/cloudflare-drizzle-d1/README.md Use these commands to initialize your local D1 database with migration files and start the local development server. ```bash npm run wrangler d1 execute --local --file=./drizzle/0000_sudden_brother_voodoo.sql npm run dev ``` -------------------------------- ### Install Pylon Dependencies for Bun Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx Install the necessary Pylon development and runtime packages using Bun. This command should be run in your project's root directory. ```sh bun add -D @getcronit/pylon-dev bun add @getcronit/pylon ``` -------------------------------- ### Define Pylon Service with Prisma Integration Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx This example demonstrates how to define a Pylon service that uses Prisma to interact with a database. It includes example GraphQL queries and mutations for fetching and creating user data. ```typescript import {app} from '@getcronit/pylon' import {PrismaClient} from '@prisma/client' const prisma = new PrismaClient() export const graphql = { Query: { // Example query using Prisma getUser: async (id: number) => { return await prisma.user.findUnique({ where: {id} }) } }, Mutation: { // Example mutation using Prisma createUser: async (data: any) => { return await prisma.user.create({ data }) } } } export default app ``` -------------------------------- ### Update Start Script for Pylon v2 Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/release-notes/migrating-from-v1-to-v2.mdx Modify your start script to use the new `pylon dev` command, specifying the runtime command with the `-c` flag. ```diff { "scripts": { - "develop": "bun run pylon develop" + "dev": "pylon dev -c 'bun run .pylon/index.js'" } } ``` -------------------------------- ### Create New Pylon Project Source: https://github.com/getcronit/pylon/blob/main/packages/pylon/README.md Run this command to initialize a new Pylon project. Navigate to the project directory and start the development server with `npm run dev`. ```bash npm create pylon@latest cd my-pylon npm run dev ``` -------------------------------- ### GraphQL Query Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Demonstrates how to query for user data, including nested address information, using a GraphQL query. ```graphql query { getUser(id: 1) { id name age address { street city zipCode } } } ``` -------------------------------- ### Start Pylon Development Server for Cloudflare Workers Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-2.0.mdx Starts the Pylon development server specifically configured for Cloudflare Workers using the 'wrangler dev' command. ```bash pylon dev -c 'wrangler dev' ``` -------------------------------- ### Install Pylon Dependencies for Node.js Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx Install the necessary Pylon development and runtime packages using npm for Node.js. This command should be run in your project's root directory. ```sh npm install --save-dev @getcronit/pylon-dev bun add @getcronit/pylon ``` -------------------------------- ### Pothos Schema Definition Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/faq.mdx Illustrates how to define a simple 'hello' query using Pothos. Note the explicit schema definition. ```typescript import { createYoga } from 'graphql-yoga'; import { createServer } from 'node:http'; import SchemaBuilder from '@pothos/core'; const builder = new SchemaBuilder({}); builder.queryType({ fields: (t) => ({ hello: t.string({ args: { name: t.arg.string(), }, resolve: (parent, { name }) => `hello, ${name || 'World'}`, }), }), }); ... ``` -------------------------------- ### GraphQL Mutation Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Illustrates how to update user information, including nested address details, using a GraphQL mutation. ```graphql mutation { updateUser( user: { id: 1 name: "Jane Doe" age: 30 address: {street: "456 Elm St", city: "Othertown", zipCode: "67890"} } ) { id name age address { street city zipCode } } } ``` -------------------------------- ### Pylon GraphQL Mutation Example with Error Handling Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/logging-and-monitoring.mdx This example demonstrates a GraphQL mutation in Pylon that includes error handling for division by zero and logs informational messages. Errors and logs are automatically sent to Sentry if SENTRY_DSN is configured. ```typescript import {app} from '@getcronit/pylon' export const graphql = { Mutation: { divide: (a: number, b: number) => { if (b === 0) { console.error('Attempt to divide by zero') throw new Error('Division by zero is not allowed') } console.info(`Dividing ${a} by ${b}`) return a / b } } } export default app ``` -------------------------------- ### Dockerfile for Pylon with Bun Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx This Dockerfile sets up a production environment for a Pylon application using Bun. It optimizes dependency caching and installs production dependencies separately. ```docker # use the official Bun image # see all versions at https://hub.docker.com/r/oven/bun/tags FROM oven/bun:1 as base LABEL description="Offical docker image for Pylon services (Bun)" LABEL org.opencontainers.image.source="https://github.com/getcronit/pylon" LABEL maintainer="office@cronit.io" WORKDIR /usr/src/pylon # install dependencies into temp directory # this will cache them and speed up future builds FROM base AS install RUN mkdir -p /temp/dev COPY package.json bun.lockb /temp/dev/ RUN cd /temp/dev && bun install --frozen-lockfile # install with --production (exclude devDependencies) RUN mkdir -p /temp/prod COPY package.json bun.lockb /temp/prod/ RUN cd /temp/prod && bun install --frozen-lockfile --production # copy node_modules from temp directory # then copy all (non-ignored) project files into the image FROM install AS prerelease COPY --from=install /temp/dev/node_modules node_modules COPY . . # [optional] tests & build ENV NODE_ENV=production # Create .pylon folder (mkdir) RUN mkdir -p .pylon # RUN bun test RUN bun run pylon build # copy production dependencies and source code into final image FROM base AS release COPY --from=install /temp/prod/node_modules node_modules COPY --from=prerelease /usr/src/pylon/.pylon .pylon COPY --from=prerelease /usr/src/pylon/package.json . # run the app USER bun EXPOSE 3000/tcp ENTRYPOINT [ "bun", "run", "/usr/src/pylon/.pylon/index.js" ] ``` -------------------------------- ### Setting Environment Bindings with .env File Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/bindings-and-variables.mdx Provides an example of how to set environment bindings, such as `SECRET`, using a `.env` file. This is a common method for managing sensitive configuration data locally. ```env SECRET=your-secret ``` -------------------------------- ### Example GraphQL Query for Product List Source: https://github.com/getcronit/pylon/blob/main/packages/pylon/README.md This GraphQL query fetches a list of products, including their ID, name, and price. The `products` query must be implemented in your service. ```graphql query GetProducts { products { id name price } } ``` -------------------------------- ### Example GraphQL Query Source: https://github.com/getcronit/pylon/blob/main/README.md This GraphQL query retrieves user information including ID, name, and email. It also demonstrates fetching a list of products with their ID, name, and price. ```graphql query GetUser { user(id: "1") { id name email } } query GetProducts { products { id name price } } ``` -------------------------------- ### GraphQL Query Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/automatic-graphql-api-generation.mdx Execute a GraphQL query to call the 'sum' operation with specific arguments. ```graphql query { sum(a: 5, b: 3) } ``` -------------------------------- ### GraphQL Query Result Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Shows the expected JSON response structure for a successful `getUser` GraphQL query. ```json { "data": { "getUser": { "id": 1, "name": "John Doe", "age": 25, "address": { "street": "123 Main St", "city": "Anytown", "zipCode": "12345" } } } } ``` -------------------------------- ### Create a Logging Decorator Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/decorators.mdx Demonstrates creating a custom decorator using `createDecorator` to log execution before a service function runs. This example applies the decorator to a class method. ```typescript import {app, createDecorator} from '@getcronit/pylon' const log = createDecorator(async () => { console.log('Executing service function') }) class Foo { @log foo = async () => { return 'foo' } } export default app ``` -------------------------------- ### GraphQL Mutation Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/automatic-graphql-api-generation.mdx Execute a GraphQL mutation to call the 'divide' operation with specific arguments. ```graphql mutation { divide(a: 10, b: 2) } ``` -------------------------------- ### GraphQL Mutation Result Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Presents the expected JSON response structure after a successful `updateUser` GraphQL mutation. ```json { "data": { "updateUser": { "id": 1, "name": "Updated Name", "age": 30, "address": { "street": "456 Elm St", "city": "Othertown", "zipCode": "67890" } } } } ``` -------------------------------- ### Pylon Schema Inference Example Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/faq.mdx Shows how Pylon infers the schema from TypeScript types for a 'hello' query. No explicit schema definition is required. ```typescript import {app} from '@getcronit/pylon' export const graphql = { Query: { hello: (name: string) => { return `hello, ${name || 'World'}` } } } export default app ``` -------------------------------- ### Example GraphQL Mutation to Create an Order Source: https://github.com/getcronit/pylon/blob/main/packages/pylon/README.md This mutation creates a new order for a given user and a list of product IDs. The `createOrder` mutation must be implemented in your service. ```graphql mutation CreateOrder { createOrder(userId: "1", productIds: ["1", "2"]) { id userId productIds status } } ``` -------------------------------- ### Dockerfile for Prisma Deployment Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx This Dockerfile configures a Pylon project with Prisma, ensuring schema and migrations are included during deployment. It caches dependencies and separates development and production installations. ```docker # use the official Bun image # see all versions at https://hub.docker.com/r/oven/bun/tags FROM oven/bun:1 as base LABEL description="A Pylon project with Prisma" LABEL org.opencontainers.image.source="https://github.com/cronitio/my-pylon-project" LABEL maintainer="opensource@cronit.io" WORKDIR /usr/src/pylon # install dependencies into temp directory # this will cache them and speed up future builds FROM base AS install ARG NODE_VERSION=20 RUN apt update && apt install -y curl RUN curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n && bash n $NODE_VERSION && rm n && npm install -g n RUN mkdir -p /temp/dev COPY package.json bun.lockb /temp/dev/ COPY prisma /temp/dev/prisma RUN cd /temp/dev && bun install --frozen-lockfile RUN cd /temp/dev && bun prisma generate # install with --production (exclude devDependencies) RUN mkdir -p /temp/prod COPY package.json bun.lockb /temp/prod/ COPY prisma /temp/prod/prisma RUN cd /temp/prod && bun install --frozen-lockfile --production RUN cd /temp/prod && bun prisma generate # copy node_modules from temp directory # then copy all (non-ignored) project files into the image FROM install AS prerelease COPY --from=install /temp/dev/node_modules node_modules COPY . . # [optional] tests & build ENV NODE_ENV=production # Create .pylon folder (mkdir) RUN mkdir .pylon # RUN bun test RUN bun run pylon build # copy production dependencies and asource code into final image FROM base AS release RUN apt-get update -y && apt-get install -y openssl COPY --from=install /temp/prod/node_modules node_modules COPY --from=prerelease /usr/src/pylon/.pylon .pylon COPY --from=prerelease /usr/src/pylon/package.json . COPY --from=prerelease /usr/src/pylon/prisma prisma # run the app USER bun EXPOSE 3000/tcp ENTRYPOINT [ "bun", "run", "./node_modules/.bin/pylon-server" ] ``` -------------------------------- ### Dockerfile for Pylon with Node.js Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx This Dockerfile sets up a production environment for a Pylon application using Node.js 20. It optimizes dependency caching and installs production dependencies separately. ```docker # Use the official Node.js 20 image as the base FROM node:20-alpine as base LABEL description="Offical docker image for Pylon services (Node.js)" LABEL org.opencontainers.image.source="https://github.com/getcronit/pylon" LABEL maintainer="office@cronit.io" WORKDIR /usr/src/pylon # install dependencies into a temp directory # this will cache them and speed up future builds FROM base AS install RUN mkdir -p /temp/dev COPY package.json package-lock.json /temp/dev/ RUN cd /temp/dev && npm ci # install with --production (exclude devDependencies) RUN mkdir -p /temp/prod COPY package.json package-lock.json /temp/prod/ RUN cd /temp/prod && npm ci --only=production # copy node_modules from temp directory # then copy all (non-ignored) project files into the image FROM install AS prerelease COPY --from=install /temp/dev/node_modules node_modules COPY . . # [optional] tests & build ENV NODE_ENV=production # Create .pylon folder (mkdir) RUN mkdir -p .pylon # RUN npm test RUN npm run pylon build # copy production dependencies and source code into final image FROM base AS release COPY --from=install /temp/prod/node_modules node_modules COPY --from=prerelease /usr/src/pylon/.pylon .pylon COPY --from=prerelease /usr/src/pylon/package.json . # run the app USER node EXPOSE 3000/tcp ENTRYPOINT [ "node", "/usr/src/pylon/.pylon/index.js" ] ``` -------------------------------- ### Usage of Extended Prisma Models in Pylon Service Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx Example demonstrating how to import and use extended Prisma models (Post) within a Pylon GraphQL service for queries and mutations. Relations are resolved automatically. ```typescript import {app} from '@getcronit/pylon' import {Post} from '../repository/models' export const graphql = { Query: { // Example query using extended Prisma models getPost: async (id: number) => { return await Post.get({ id }) }, allPosts: async () => { return await Post.paginate() } }, Mutation: { // Example mutation using extended Prisma models createPost: async (data: any) => { return await Post.create({ data }) } } } export default app ``` -------------------------------- ### MongoDB Integration with Pylon Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx Example of integrating MongoDB with Pylon. This snippet demonstrates setting up a MongoDB client, defining collections, and implementing GraphQL queries and mutations to interact with the database. Ensure proper type definitions for type safety. ```typescript import {app} from '@getcronit/pylon' import {MongoClient} from 'mongodb' const uri = 'mongodb://localhost:27017' const client = new MongoClient(uri) // Define MongoDB collections let usersCollection: any ;(async () => { await client.connect() const database = client.db('myDatabase') usersCollection = database.collection('users') })() export const graphql = { Query: { // Example query using MongoDB getUser: async (id: string) => { return await usersCollection.findOne({_id: id}) } }, Mutation: { // Example mutation using MongoDB createUser: async (user: any) => { await usersCollection.insertOne(user) return user } } } export default app ``` -------------------------------- ### Implement REST API GET /posts Endpoint Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/testing.mdx Implements a REST API endpoint to fetch all posts. This code should be added to your main application file. ```typescript import {app} from '@getcronit/pylon' const posts: {id: number; title: string; content: string}[] = [ { id: 1, title: 'Hello, world!', content: 'This is the first post' }, { id: 2, title: 'Hello, Pylon!', content: 'This is the second post' } ] export const graphql = { // ... (previous code remains unchanged) } app.get('/posts', c => { return c.json(posts) }) export default app ``` -------------------------------- ### Applying Hono Middleware as Decorators Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/decorators.mdx Integrate Hono middleware, like `basicAuth`, into Pylon service functions using `createDecorator`. This example secures the `secure` query with basic authentication. ```typescript import {app, createDecorator, getContext} from '@getcronit/pylon' import {basicAuth} from 'hono/basic-auth' const authMiddleware = basicAuth({ username: 'admin', password: 'password' }) const requireBasicAuth = createDecorator(async () => { const ctx = getContext() await authMiddleware(ctx, async () => {}) // Pass an empty next function }) export const graphql = { Query: { secure: requireBasicAuth(() => { return 'You are authenticated!' }) } } app.get('/', authMiddleware, c => { return new Response('Hello World') }) export default app ``` -------------------------------- ### Initialize Pylon Authentication with ZITADEL Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/built-in-authentication-and-authorization.mdx This example demonstrates how to initialize Pylon's authentication middleware using ZITADEL. The `requireAuth()` decorator is used to protect sensitive data endpoints, ensuring only authenticated users can access them. ```typescript import {app, auth, requireAuth} from '@getcronit/pylon' // Define your sensitive data service class SensitiveData { @requireAuth() static async getData() { return 'Sensitive Data' } } export const graphql = { Query: { sensitiveData: SensitiveData.getData } } app.use('*', auth.initialize()) export default app ``` -------------------------------- ### Create a Sub-Router with Hono for Pylon Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/context-management.mdx To avoid conflicts when using Pylon's app instance, create sub-routers using a new Hono instance. This example defines an authentication router that can be later mounted onto the main Pylon app. ```typescript import {type Bindings, type Variables} from '@getcronit/pylon' import {Hono} from 'hono' const authRouter = new Hono<{ Bindings: Bindings Variables: Variables }>() authRouter.get('/', c => { return c.text('Hello from Auth') }) export default authRouter ``` -------------------------------- ### Define GraphQL Schema and Mutations Source: https://github.com/getcronit/pylon/blob/main/README.md Define your GraphQL queries and mutations using TypeScript. This example shows how to set up user and product queries, and user email update and order creation mutations. ```typescript import {app} from '@getcronit/pylon' export const graphql = { Query: { user: (id: string) => { return { id, name: 'John Doe', email: 'johndoe@example.com' } }, products: () => [ {id: '1', name: 'Laptop', price: 999.99}, {id: '2', name: 'Smartphone', price: 499.99}, {id: '3', name: 'Tablet', price: 299.99} ] }, Mutation: { updateUserEmail: (id: string, newEmail: string) => { return { id, email: newEmail } }, createOrder: (userId: string, productIds: string[]) => { return { id: 'order-123', userId, productIds, status: 'PENDING' } } } } export default app ``` -------------------------------- ### Example GraphQL Query for User Data Source: https://github.com/getcronit/pylon/blob/main/packages/pylon/README.md This GraphQL query retrieves a user's ID, name, and email. Ensure the `user` query and its fields are defined in your service. ```graphql query GetUser { user(id: "1") { id name email } } ``` -------------------------------- ### Define GraphQL Schema and Basic Route with Pylon App Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/context-management.mdx This snippet shows how to define GraphQL resolvers and a basic GET route using the Pylon app instance, which is an alias for the Hono application. Ensure only one import of the Pylon app instance to avoid conflicts. ```typescript import {app} from '@getcronit/pylon' export const graphql = { Query: { sum: (a: number, b: number) => a + b }, Mutation: { divide: (a: number, b: number) => a / b } } app.get('/hello', (ctx, next) => { return new Response('Hello, world!') }) export default app ``` -------------------------------- ### Example GraphQL Mutation Source: https://github.com/getcronit/pylon/blob/main/README.md This GraphQL mutation updates a user's email address. It also shows how to create a new order, specifying the user ID and a list of product IDs. ```graphql mutation UpdateUserEmail { updateUserEmail(id: "1", newEmail: "johndoe2@example.com") { id email } } mutation CreateOrder { createOrder(userId: "1", productIds: ["1", "2"]) { id userId productIds status } } ``` -------------------------------- ### Pylon GraphQL API with TypeScript Union and Interface Support Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-2.3.mdx Example demonstrating how to define a GraphQL schema using TypeScript unions and interfaces with Pylon, including automatic type resolution. ```typescript import {app, ID} from '@getcronit/pylon' type Node = User | Post interface User { id: ID name: string } interface Post { id: ID title: string } const nodes: Node[] = [ {id: '1', name: 'John Doe'}, {id: '2', name: 'Jane Doe'}, {id: '3', title: 'Hello, World!'}, {id: '4', title: 'Hello, Pylon!'} ] export const graphql = { Query: { node: (id: ID): Node => { const node = nodes.find(node => node.id === id) if (!node) throw new Error('Node not found') return node } } } export default app ``` -------------------------------- ### Define Pylon Service with TypeScript Types Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Demonstrates defining a Pylon service using various TypeScript type variants including types, interfaces, enums, and classes. This example shows how to define queries and mutations with these types. ```typescript import {app} from '@getcronit/pylon' // Define a type type Address = { street: string city: string zipCode: string } // Define an interface interface User { id: number name: string age: number address: Address } // Define an enum enum Status { ACTIVE = 'ACTIVE', INACTIVE = 'INACTIVE' } // Define a class class Product { constructor(public id: number, public name: string, public price: number) {} } export const graphql = { Query: { getUser: (id: number): User => { return { id, name: 'John Doe', age: 25, address: {street: '123 Main St', city: 'Anytown', zipCode: '12345'} } }, getProduct: (id: number): Product => { return new Product(id, 'Example Product', 99.99) }, getStatus: (): Status => { return Status.ACTIVE } }, Mutation: { updateUser: (user: User): User => { return {...user, name: 'Updated Name'} }, updateProduct: (product: Product): Product => { product.price = 79.99 return product } } } export default app ``` -------------------------------- ### Pylon TypeScript Declaration File Setup Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/bindings-and-variables.mdx Defines the basic structure for Pylon's TypeScript declaration file, `pylon.d.ts`, which is essential for type safety. This file should be included in your `tsconfig.json`. ```typescript // pylon.d.ts import '@getcronit/pylon' declare module '@getcronit/pylon' { interface Bindings {} interface Variables {} } ``` ```json { "include": ["pylon.d.ts", "src/**/*.ts"] } ``` -------------------------------- ### Integrate Envelop Error Handler Plugin in Pylon Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/plugins.mdx This example demonstrates how to import and configure the `useErrorHandler` Envelop plugin within a Pylon application's configuration. It shows how to catch and log GraphQL errors. ```typescript import {app, PylonConfig, ServiceError} from '@getcronit/pylon' import {useErrorHandler} from '@envelop/core' export const graphql = { Query: { hello: () => { throw new ServiceError('Hello, world!', { code: 'HELLO_WORLD', statusCode: 400 }) } }, Mutation: {} } export const config: PylonConfig = { plugins: [ useErrorHandler(({errors, context, phase}) => { console.error(errors) }) ] } export default app ``` -------------------------------- ### Create Pylon Project with GQty Client Generation Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/gqty.mdx This command-line interaction shows how to create a new Pylon project and configure it to generate a GQty client. It prompts for project details, runtime, template, and client generation settings, including the output path and server port. ```bash create-pylon version 1.0.0 4:55:00 PM ? Target directory my-pylon ? Which runtime would you like to use? Bun.js (https://bunjs.dev) ? Which template would you like to use? Default ? Would you like to install dependencies? no ◐ Creating pylon in /Users/schettn/Documents/my-pylon 4:55:11 PM ✔ Pylon created 4:55:11 PM ? Would you like to enable client generation? (https://pylon.cronit.io/docs/integrations/gqty) yes ? Path to the root where the client should be generated . ? Path to generate the client to gqty/index.ts ? Port of the pylon server to generate the client from 3000 ◐ Updating pylon dev script to generate client 4:55:20 PM ✔ Pylon dev script updated 4:55:20 PM ╭───────────────────────────────────────────╮ │ │ │ Pylon successfully created in my-pylon. │ │ │ │ Happy coding! │ │ │ ╰───────────────────────────────────────────╯ ``` -------------------------------- ### App Root Component with Vercel Analytics Source: https://github.com/getcronit/pylon/blob/main/docs/pages/_app.mdx This snippet shows the standard setup for a Next.js application's root component (`_app.js` or `_app.tsx`) to include Vercel Analytics. Ensure the Analytics component is placed within the root layout to track all page views. ```javascript import {Analytics} from '@vercel/analytics/react' import '../styles/globals.css' export default function MyApp({Component, pageProps}) { return ( <> ) } ``` -------------------------------- ### Create New Pylon Project Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-1.0.mdx Initialize a new Pylon project using the Pylon CLI. ```bash pylon new my-pylon-project ``` -------------------------------- ### Set Up Basic Pylon Application Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/testing.mdx Initializes a basic Pylon application with an empty posts array. This serves as the foundation for further development. ```typescript import {app} from '@getcronit/pylon' const posts: {id: number; title: string; content: string}[] = [] export default app ``` -------------------------------- ### Semantic Commit Type Examples Source: https://github.com/getcronit/pylon/blob/main/CONTRIBUTING.md Examples of common commit types used in semantic commit conventions. These help categorize the nature of the changes being made. ```git commit feat(auth): add login functionality ``` ```git commit fix(profile): correct user profile picture URL ``` -------------------------------- ### Create a New Pylon Project Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/getting-started.mdx Use this command to scaffold a new Pylon project. It initializes a basic project structure with default configurations. ```bash npm create pylon my-pylon@latest ``` -------------------------------- ### Test REST API GET /posts Endpoint Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/testing.mdx Tests the REST API GET /posts endpoint to ensure it returns the correct list of posts. Assumes the application has been built. ```typescript import {describe, expect, test} from 'bun:test' // Make sure to run `bun run build` before running the tests import app from './.pylon/index' describe('GraphQL API', () => { // ... (previous tests remains unchanged) }) describe('REST API', () => { test('GET /posts', async () => { const res = await app.request('/posts') expect(res.status).toBe(200) const data = await res.json() expect(data).toEqual([ { id: 1, title: 'Hello, world!', content: 'This is the first post' }, { id: 2, title: 'Hello, Pylon!', content: 'This is the second post' }, { id: 3, title: 'New Post', content: 'This is a new post' } ]) }) }) ``` -------------------------------- ### Build and Run Pylon Docker Image Source: https://github.com/getcronit/pylon/blob/main/README.md Use these commands to build a Docker image for your Pylon service and run it. Ensure you are in the directory containing the Dockerfile. ```bash docker build -t my-pylon . docker run -p 3000:3000 my-pylon ``` -------------------------------- ### Get All Bookings Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/building-with-pylon/integrating-prisma.mdx Fetches all bookings from the database. This function is intended to be registered with Pylon's GraphQL API. ```typescript export async function getBookings(): Promise { return await db.booking.findMany() } ``` -------------------------------- ### Build Pylon Project for Production Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/getting-started.mdx Compile your Pylon project for deployment. This command generates an optimized build in the `.pylon` directory. ```bash npm run build ``` -------------------------------- ### Define a TypeScript Union for Newsfeed Items Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/interfaces-and-unions.mdx Example of a TypeScript union type representing different kinds of newsfeed items, such as status updates or photos. ```typescript type Status = { id: ID text: string author: User } type Photo = { id: ID url: string caption: string } type NewsfeedItem = Status | Photo export const graphql = { Query: { newsfeed: (): NewsfeedItem[] => { // Implementation to fetch newsfeed items } } } ``` -------------------------------- ### Provide Prisma Client Instance Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/building-with-pylon/integrating-prisma.mdx This code provides a singleton instance of the Prisma client, ensuring type safety. It's typically placed in a `lib/db.ts` file within your Pylon project. ```typescript import {PrismaClient} from '@prisma/client' declare global { var prisma: PrismaClient | undefined } export const db = globalThis.prisma || new PrismaClient() if (process.env.NODE_ENV !== 'production') globalThis.prisma = db ``` -------------------------------- ### Prisma Schema Definition Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/building-with-pylon/integrating-prisma.mdx Example Prisma schema defining 'Booking' and 'BookingDates' models. This schema is used to generate type-safe database access methods. ```prisma model Booking { id Int @id @default(autoincrement()) firstname String lastname String totalprice Float depositpaid Boolean bookingdates BookingDates? @relation(fields: [bookingDatesId], references: [id]) additionalneeds String? bookingDatesId Int } model BookingDates { id Int @id @default(autoincrement()) checkin String checkout String booking Booking[] } ``` -------------------------------- ### Argument Validation Decorator Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/decorators.mdx Use `createDecorator` to create custom decorators for validating service function arguments. This example enforces a minimum password length. ```typescript import {app, createDecorator, ServiceError} from '@getcronit/pylon' const validatePassword = createDecorator( async (username: string, password: string) => { if (password.length < 8) { throw new ServiceError('Password must be at least 8 characters long', { code: 'INVALID_PASSWORD', statusCode: 400 }) } } ) export const graphql = { Query: { hello: 'Hello World!' }, Mutation: { login: validatePassword((username: string, password: string) => { return `Welcome, ${username}!` }) } } export default app ``` -------------------------------- ### Directory Structure Verification Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx This is the expected project directory structure after setting up Pylon. Ensure 'Index.ts' is directly under the 'src' directory. ```text my-pylon │ ├── .dockerignore ├── .gitignore ├── bun.lockb ├── Dockerfile ├── package.json ├── pylon.d.ts ├── tsconfig.json │ └───src └──index.ts ``` -------------------------------- ### Execute Migration Files on Production D1 Source: https://github.com/getcronit/pylon/blob/main/examples/cloudflare-drizzle-d1/README.md Apply your generated migration files to the production D1 database using this command. ```bash npm run wrangler d1 execute --remote --file=./drizzle/0000_sudden_brother_voodoo.sql ``` -------------------------------- ### Update Dockerfile ENTRYPOINT Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/release-notes/migrating-from-v1-to-v2.mdx Change the Dockerfile's `ENTRYPOINT` to use the new Pylon index file path instead of the `pylon-server` command. ```diff - ENTRYPOINT [ "bun", "run", "./node_modules/.bin/pylon-server" ] + ENTRYPOINT [ "bun", "run", "/usr/src/pylon/.pylon/index.js" ] ``` -------------------------------- ### GraphQL Resolver Throwing ServiceError Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/plugins.mdx This example defines a GraphQL query resolver that intentionally throws a `ServiceError` to demonstrate how Envelop plugins can intercept and handle such errors. ```typescript export const graphql = { Query: { hello: () => { throw new ServiceError('Hello, world!', { code: 'HELLO_WORLD', statusCode: 400 }) } }, Mutation: {} } ``` -------------------------------- ### Mocking Dependencies with Direct Import Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/testing.mdx Import and use the './src/index.ts' file directly in tests to mock dependencies. Manually set up the handler for GraphQL requests. ```typescript import {handler} from '@getcronit/pylon' import app, {graphql} from './src/index' app.use(handler({graphql})) ... your tests here ... ``` -------------------------------- ### Initial Pylon Index File Structure Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/building-with-pylon/hardcoded-data.mdx The initial structure of the index.ts file before registering custom methods. It includes basic Pylon app import and a default 'hello' query. ```typescript import {app} from '@getcronit/pylon' export const graphql = { Query: { hello: () => 'Hello World' }, Mutation: {} } export default app ``` -------------------------------- ### Securing Routes with requireAuth Middleware Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/built-in-authentication-and-authorization.mdx Enforce authentication and authorization for specific routes using the requireAuth middleware. This example secures the '/admin' route, requiring the 'admin' role. ```typescript import {auth, requireAuth} from '@getcronit/pylon' // Define your sensitive data service class SensitiveData { static async getData() { return 'Sensitive Data' } @requireAuth({ roles: ['admin'] }) static async getAdminData() { return 'Admin Data' } } export const graphql = { Query: { sensitiveData: SensitiveData.getData, sensitiveAdminData: SensitiveData.getAdminData } } // Enforce authentication for all routes app.use('*', auth.initialize()) // Secure a specific route with authentication and authorization app.use('/admin', auth.requireAuth({roles: ['admin']})) export default app ``` -------------------------------- ### Authorization with requireAuth Decorator Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/built-in-authentication-and-authorization.mdx Use the @requireAuth decorator to restrict access to functions based on user roles. This example restricts access to 'getAdminData' to users with the 'admin' role. ```typescript class SensitiveData { @requireAuth({ roles: ['admin'] }) static async getAdminData() { return 'Admin Data' } } export const graphql = { Query: { sensitiveAdminData: SensitiveData.getAdminData } } app.use('*', auth.initialize()) export default app ``` -------------------------------- ### Generate Extended Prisma Models Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx Run the generation command to create extended Prisma models for your Pylon project. ```bash bunx prisma-extended-models generate ``` -------------------------------- ### Type-Safe Functions Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Ensure type safety for function parameters and return values by using TypeScript's type annotations. This example defines a function that returns a User object. ```typescript const getUser = (id: number): User => { return { id, name: 'John Doe', age: 25, address: {street: '123 Main St', city: 'Anytown', zipCode: '12345'} } } ``` -------------------------------- ### Create Object Instances with Classes Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/type-safety-and-type-integration.mdx Utilize classes to define blueprints for objects, including their properties and methods. The `constructor` initializes the object's state. ```typescript class Product { constructor( public id: number, public name: string, public price: number ) {} } ``` -------------------------------- ### Import Pylon App Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/automatic-graphql-api-generation.mdx Import the 'app' instance from the '@getcronit/pylon' package to initialize your Pylon application. ```typescript import {app} from '@getcronit/pylon' ``` -------------------------------- ### Create pylon.d.ts Declaration File Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/convert-from-hono-guide.mdx Create a `pylon.d.ts` file in your project root to provide type definitions for Pylon, including interfaces for Bindings and Variables. ```typescript import '@getcronit/pylon' declare module '@getcronit/pylon' { interface Bindings {} interface Variables {} } ``` -------------------------------- ### Access Request Context with getContext Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/core-concepts/context-management.mdx Use `getContext` within service functions to retrieve request-specific data like headers and parameters. This example demonstrates checking an 'X-API-Key' header for authorization. ```typescript import {app, getContext} from '@getcronit/pylon' export const graphql = { Query: { protected: () => { const ctx = getContext() const header = ctx.req.header('X-API-Key') if (header !== 'secret') { return new Response('Unauthorized', {status: 401}) } return new Response('The secret is safe with me!') } } } export default app ``` -------------------------------- ### GraphQL Query for Paginated Posts with Resolved Authors Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/integrations/databases.mdx Example GraphQL query to fetch paginated posts, including their associated author details. The extended models automatically resolve the author relation. ```graphql query { allPosts { edges { node { id title content author { id name } } } } } ``` -------------------------------- ### Generate Migration Files Source: https://github.com/getcronit/pylon/blob/main/examples/cloudflare-drizzle-d1/README.md Run this command after making changes to your schema file (./src/schema.ts) to generate new migration files. ```bash npm run generate ``` -------------------------------- ### Run Pylon Tests Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/testing.mdx Command to execute the tests for your Pylon application using Bun. ```shellscript bun test ``` -------------------------------- ### Example GraphQL Mutation to Update User Email Source: https://github.com/getcronit/pylon/blob/main/packages/pylon/README.md This mutation updates a user's email address. It requires the user's ID and the new email as arguments. The `updateUserEmail` mutation must be defined in your service. ```graphql mutation UpdateUserEmail { updateUserEmail(id: "1", newEmail: "johndoe2@example.com") { id email } } ``` -------------------------------- ### Fetch Booking by ID using Pylon Source: https://github.com/getcronit/pylon/blob/main/docs/pages/docs/guides/building-with-pylon/external-api.mdx Implement a method to fetch booking details from an external API using the booking ID. This method makes a GET request to the specified URL and returns the JSON response. ```typescript async getBookingById(bookingId: number): Promise { const url = `https://restful-booker.herokuapp.com/booking/${bookingId}`; const response = await fetch(url); const data = await response.json(); return data; } ``` -------------------------------- ### Create Pylon Project with Cloudflare Workers Runtime Source: https://github.com/getcronit/pylon/blob/main/docs/pages/blog/pylon-2.0.mdx Use this command to create a new Pylon project specifically configured for the Cloudflare Workers runtime. The `--runtime` flag allows selection of other supported runtimes as well. ```bash npm create pylon --runtime cf-workers ```