Skip to content

Instantly share code, notes, and snippets.

View akoenig's full-sized avatar
🐝

André König akoenig

🐝
View GitHub Profile
@akoenig
akoenig / pattern-matching.ts
Created December 19, 2023 16:15
Pattern Matching in TypeScript
//
// This is a code example from the blog post:
//
// https://andrekoenig.de/articles/pattern-matching-in-typescript
//
import { P, match } from "ts-pattern";
type ProductWasAddedToCartEvent = Readonly<{
type: "ProductWasAddedToCart";

Keybase proof

I hereby claim:

  • I am akoenig on github.
  • I am andrekoenig (https://keybase.io/andrekoenig) on keybase.
  • I have a public key ASAP9kw2P5vzONNZiY8kA4JgNR_tAq7sahvVNtBXnZ3-ewo

To claim this, I am signing this object:

@akoenig
akoenig / middleware-example.js
Created May 10, 2018 15:40
GraphQL: Hand rolled middleware mechanism
const aFieldResolver = (parent, args, context, info) => "beeeeeeeeep";
const myCustomMiddleware = async (parent, args, context, info) => {
// Will be executed before the resolver
};
const middleware = (middlewares, resolver) => async (...args) => {
for (const middleware of middlewares) {
await middleware(...args);
telemetry-consumer:
schemaPath: ./binding/telemetry.graphql
extensions:
+ prepare-binding:
+ output: ./binding/telemetry.ts
+ generator: binding-ts
endpoints:
telemetry: 'https://kqxrmk1pr7.lp.gql.zone/graphql'
mkdir telemetry-consumer && cd $_
# Create directory for the binding
mkdir binding
# Install the `graphql-cli` locally
yarn add graphql-cli
yarn graphql init
? Enter project name (Enter to skip): telemetry-consumer
// path: resolvers/mutation/index.ts
import { helmet } from "../helmet";
import { login } from "./login";
const Mutation = {
login: helmet(login)
// ...
};
// path: resolvers/helmet.ts
import { FatalError } from "./errors/FatalError";
const helmet = (resolver) => async (...args) => {
try {
//
// Try to execute the actual resolver and return
// the result immediately.
//
import { GraphQLServer, Options } from "graphql-yoga";
import { formatError } from "apollo-errors";
const options: Options = {
formatError
};
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(options, () => console.log('GraphQL API is running on localhost:4000'))
{
"data": {},
"errors": [
{
"message":"The provided credentials are invalid.",
"name":"WrongCredentialsError",
"time_thrown":"2018-02-14T00:40:50.954Z",
}
]
}
// path: resolvers/mutation/login/index.ts
import { WrongCredentialsError } from "./errors/WrongCredentialsError";
interface LoginInput {
username: string;
password: string;
}
const login = await (parent, args: LoginInput, context: Context, info) {