Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Implement Dockerized Deno GraphQL server #9

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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.git
9 changes: 8 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,12 @@
"frontend/build/**": true,
"frontend/src/tailwind.output.css": true
},
"typescript.tsdk": "./frontend/node_modules/typescript/lib"
"typescript.tsdk": "./frontend/node_modules/typescript/lib",
"deno.enable": true,
"deno.lint": true,
"deno.unstable": true,
"deno.import_intellisense_origins": {
"https://deno.land": true
},
"deno.import_intellisense_autodiscovery": true
}
3 changes: 3 additions & 0 deletions database.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
POSTGRES_USER=unicorn_user
POSTGRES_PASSWORD=magical_password
POSTGRES_DB=rainbow_database
42 changes: 42 additions & 0 deletions deno/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
FROM frolvlad/alpine-glibc:alpine-3.12_glibc-2.32

ENV DENO_VERSION=1.5.2

RUN apk add --virtual .download --no-cache curl \
&& curl -fsSL https://github.com/denoland/deno/releases/download/v${DENO_VERSION}/deno-x86_64-unknown-linux-gnu.zip \
--output deno.zip \
&& unzip deno.zip \
&& rm deno.zip \
&& chmod 777 deno \
&& mv deno /bin/deno \
&& apk del .download

RUN addgroup -g 1993 -S deno \
&& adduser -u 1993 -S deno -G deno \
&& mkdir /deno-dir/ \
&& chown deno:deno /deno-dir/

ENV DENO_DIR /deno-dir/
ENV DENO_INSTALL_ROOT /usr/local

# The port that your application listens to.
EXPOSE 1993

WORKDIR /app

# Prefer not to run as root.
USER deno

COPY tsconfig.json .

# Cache the dependencies as a layer (the following two steps are re-run only when deps.ts is modified).
# Ideally cache deps.ts will download and compile _all_ external files used in main.ts.
COPY deps.ts .
RUN deno cache deps.ts -c tsconfig.json --unstable

# These steps will be re-run upon each file change in your working directory:
ADD . .
# Compile the main app so that it doesn't need to be compiled each startup/entry.
RUN deno cache main.ts -c tsconfig.json --unstable

CMD ["deno", "run", "--allow-net", "--unstable", "main.ts"]
9 changes: 9 additions & 0 deletions deno/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Database } from "./deps.ts";

export const db = new Database("postgres", {
database: "rainbow_database",
host: "database",
username: "unicorn_user",
password: "magical_password",
port: 5432, // optional
});
13 changes: 13 additions & 0 deletions deno/deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export { Application, Router } from "https://deno.land/x/[email protected]/mod.ts";
export type { RouterContext } from "https://deno.land/x/[email protected]/mod.ts";
export {
applyGraphQL,
gql,
GQLError,
} from "https://deno.land/x/[email protected]/mod.ts";

export {
Model,
Database,
DataTypes,
} from "https://deno.land/x/[email protected]/mod.ts";
106 changes: 106 additions & 0 deletions deno/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { Application, Router } from "./deps.ts";
import { applyGraphQL, gql } from "./deps.ts";
import Review, { IReview } from "./models/review.ts";
import type { InputType, PayloadType } from "./types.ts";
import { db } from "./db.ts";

db.link([Review]);
await db.sync();

const app = new Application();

app.use(async (ctx, next) => {
await next();
const rt = ctx.response.headers.get("X-Response-Time");
console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`);
});

app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.response.headers.set("X-Response-Time", `${ms}ms`);
});

const types = gql`
type Review {
id: ID!
breweryId: ID!
userId: ID!
title: String!
body: String!
}
input CreateReviewInput {
clientMutationId: String!
breweryId: ID!
userId: ID!
title: String!
body: String!
}
type CreateReviewPayload {
review: Review!
clientMutationId: String!
}
type Query {
review(id: ID!): Review
reviews(breweryId: ID): [Review!]!
}
type Mutation {
createReview(input: CreateReviewInput!): CreateReviewPayload!
}
`;

const resolvers = {
Query: {
review: async (_: unknown, { id }: IReview) => {
const review = await Review.find(id);
if (review == null) {
throw new Error(
`Review with the id of '${id}' was not able to be found.`
);
}
return review;
},
reviews: async (
_: unknown,
{ breweryId }: IReview
): Promise<IReview[]> => {
if (breweryId == null) {
return await Review.all();
}

return await Review.where("breweryId", breweryId).get();
},
},
Mutation: {
createReview: async (
_: unknown,
{
input: { clientMutationId, breweryId, title, body, userId },
}: InputType<IReview>
): Promise<PayloadType<{ review: IReview }>> => {
const review: IReview = await Review.create({
body,
breweryId,
title,
userId,
});

return {
review: review,
clientMutationId,
};
},
},
};

const GraphQLService = await applyGraphQL<Router>({
Router,
typeDefs: types,
resolvers: resolvers,
});

app.use(GraphQLService.routes(), GraphQLService.allowedMethods());

console.log("Server start at http://localhost:1993");
await app.listen({ port: 1993 });
27 changes: 27 additions & 0 deletions deno/models/review.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { DataTypes, Model } from "../deps.ts";

export interface IReview {
id: number;
breweryId: number;
userId: number;
title: string;
body: string;
}

export default class Review extends Model implements IReview {
static table = "reviews";

static fields = {
id: { primaryKey: true, autoIncrement: true },
body: DataTypes.STRING,
breweryId: DataTypes.BIG_INTEGER,
title: DataTypes.STRING,
userId: DataTypes.BIG_INTEGER,
};

id!: number;
breweryId!: number;
userId!: number;
title!: string;
body!: string;
}
5 changes: 5 additions & 0 deletions deno/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"compilerOptions": {
"isolatedModules": false
}
}
11 changes: 11 additions & 0 deletions deno/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type IdType = { id: unknown };

export type InputType<T extends IdType> = {
input: Omit<T, "id"> & {
clientMutationId: string;
};
};

export type PayloadType<T> = T & {
clientMutationId: string;
};
16 changes: 16 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: "3.8"
services:
deno-graphql:
build:
context: ./deno
dockerfile: Dockerfile
ports:
- "1993:1993"
database:
image: "postgres" # use latest official postgres version
env_file:
- database.env # configure postgres
volumes:
- database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
volumes:
database-data: # named volumes can be managed easier using docker-compose
Loading