current state implementation

This commit is contained in:
Gergő Jedlicska
2024-02-05 13:48:09 +01:00
commit 2cb0daa218
21 changed files with 4658 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
export POSTGRES_URL=postgres://speckle:speckle@127.0.0.1:5454/speckle_main
+8
View File
@@ -0,0 +1,8 @@
.postgres-data
.tool-versions
.env
.envrc
.swc
node_modules
dist
+13
View File
@@ -0,0 +1,13 @@
version: "3.9"
services:
postgres:
image: postgres:16-alpine
ports:
- 5454:5432
volumes:
- ./.postgres-data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=speckle
- POSTGRES_USER=speckle
- POSTGRES_DB=speckle_main
+8
View File
@@ -0,0 +1,8 @@
export default {
client: 'pg',
connection: process.env.POSTGRES_URL,
migrations: {
directory: 'src/migrations',
extension: 'ts'
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "multi-t",
"version": "1.0.0",
"description": "",
"main": "src/app.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "ts-standard",
"tsx": "tsx",
"lint:fix": "ts-standard --fix",
"migration:make": "NODE_OPTIONS='--loader ts-node/esm' knex migrate:make",
"dev:old": "nodemon --ext ts,graphql --exec node --inspect -r @swc/register src/bin/www.ts",
"build": "tsc",
"start": "node dist/app.js",
"dev": "nodemon src/app.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^20.11.13",
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.20.0",
"concurrently": "^8.2.2",
"nodemon": "^3.0.3",
"ts-node": "^10.9.2",
"ts-standard": "^12.0.2",
"tsx": "^4.7.0",
"typescript": "^5.3.3"
},
"dependencies": {
"@apollo/server": "^4.10.0",
"dotenv": "^16.4.1",
"graphql": "^16.8.1",
"graphql-scalars": "^1.22.4",
"knex": "^3.1.0",
"pg": "^8.11.3",
"znv": "^0.4.0",
"zod": "^3.22.4"
}
}
+4042
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
import { ApolloServer } from '@apollo/server'
import { resolvers } from './resolvers'
import { startStandaloneServer } from '@apollo/server/standalone'
import { readFileSync } from 'fs'
import { typeDefs as scalarTypeDefs } from 'graphql-scalars'
import { knex } from './db'
const typeDefs = readFileSync('src/schema.graphql', { encoding: 'utf-8' })
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({
typeDefs: [typeDefs, ...scalarTypeDefs],
resolvers
})
const startServer = async (): Promise<void> => {
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 }
})
const plannedMigrations: Array<{ file: string }> = (
await knex.migrate.list()
)[1]
if (plannedMigrations.length > 0) {
console.log(
`🕰️ planning migrations: ${plannedMigrations
.map((m) => m.file)
.join(',')}`
)
}
await knex.migrate.latest()
console.log(`🚀 Server ready at: ${url}`)
}
startServer()
.then()
.catch((err: Error) =>
console.log(`🔥 failed to start server ${err.message}`)
)
+9
View File
@@ -0,0 +1,9 @@
import 'dotenv/config'
import { parseEnv } from 'znv'
import { z } from 'zod'
export const { POSTGRES_URL } = parseEnv(process.env, {
POSTGRES_URL: z.string().min(1)
})
console.log([POSTGRES_URL].join(', '))
+4
View File
@@ -0,0 +1,4 @@
import Knex from 'knex'
import config from '../knexfile'
export const knex = Knex(config)
+14
View File
@@ -0,0 +1,14 @@
import type { Knex } from 'knex'
const tableName = 'users'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.createTable(tableName, (table) => {
table.text('id').primary()
table.text('name')
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.dropTable(tableName)
}
@@ -0,0 +1,17 @@
import type { Knex } from 'knex'
const tableName = 'resources'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.createTable(tableName, (table) => {
table.text('id').primary()
table.text('name').notNullable()
table
.timestamp('createdAt', { precision: 3, useTz: true })
.defaultTo(knex.fn.now())
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.dropTable(tableName)
}
+19
View File
@@ -0,0 +1,19 @@
import type { Knex } from 'knex'
const tableName = 'comments'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.createTable(tableName, (table) => {
table.text('id').primary()
table.text('content').notNullable()
table
.timestamp('createdAt', { precision: 3, useTz: true })
.defaultTo(knex.fn.now())
table.string('userId').references('id').inTable('users')
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.dropTable(tableName)
}
@@ -0,0 +1,15 @@
import type { Knex } from 'knex'
const tableName = 'users'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.alterTable(tableName, (table) => {
table.text('name').notNullable().alter()
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.alterTable(tableName, (table) => {
table.text('name').nullable().alter()
})
}
@@ -0,0 +1,18 @@
import type { Knex } from 'knex'
const tableName = 'resource_acl'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.createTable(tableName, (table) => {
table.string('userId').references('id').inTable('users').onDelete('cascade')
table
.string('resourceId')
.references('id')
.inTable('resources')
.onDelete('cascade')
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.dropTable(tableName)
}
@@ -0,0 +1,15 @@
import type { Knex } from 'knex'
const tableName = 'comments'
export async function up (knex: Knex): Promise<void> {
return await knex.schema.alterTable(tableName, (table) => {
table.string('resourceId').references('id').inTable('resources')
})
}
export async function down (knex: Knex): Promise<void> {
return await knex.schema.alterTable(tableName, (table) => {
table.dropColumn('resourceId')
})
}
+76
View File
@@ -0,0 +1,76 @@
import { knex } from "./db";
import { UserRecord, Resource, ResourceAcl, Comment } from "./types";
const Users = () => knex<UserRecord>("users");
const Resources = () => knex<Resource>("resources");
const ResourceAclRepo = () => knex<ResourceAcl>("resource_acl");
const Comments = () => knex<Comment>("comments");
export const queryUser = async (userId: string): Promise<UserRecord | null> => {
return (await Users().where("id", "=", userId).first()) ?? null;
};
export const queryResource = async (
resourceId: string,
): Promise<Resource | null> => {
return (await Resources().where("id", "=", resourceId).first()) ?? null;
};
export const queryResourceAcl = async ({
resourceId,
userId,
}: {
resourceId: string;
userId: string;
}): Promise<ResourceAcl | null> => {
return (
(await ResourceAclRepo()
.where("userId", "=", userId)
.andWhere("resourceId", "=", resourceId)
.first()) ?? null
);
};
export const countResources = async (userId: string): Promise<number> => {
const [rawCount] = await ResourceAclRepo().count().where({ userId });
return parseInt(rawCount.count as string);
};
export const queryResources = async ({
userId,
limit,
cursor,
}: {
userId: string;
limit: number;
cursor: string | null;
}) => {
const query = Resources()
.join("resource_acl", "resources.id", "resource_acl.resourceId")
.where({ userId });
if (cursor) {
query.andWhere("createdAt", "<", cursor);
}
return await query.limit(limit);
};
export const countComments = async (resourceId: string): Promise<number> => {
const [rawCount] = await Comments().count().where({ resourceId });
return parseInt(rawCount.count as string);
};
export const queryComments = async ({
resourceId,
limit,
cursor,
}: {
resourceId: string;
limit: number;
cursor: string | null;
}): Promise<Comment[]> => {
const query = Comments().where({ resourceId });
if (cursor) {
query.andWhere("createdAt", "<", cursor);
}
return await query.limit(limit);
};
+63
View File
@@ -0,0 +1,63 @@
import { queryResourceAcl } from "./repositories";
import { getUser, getResource, getComments, getResources } from "./services";
import { GraphQLError } from "graphql";
import {
Resource,
ResourceCollection,
UserRecord,
CommentCollection,
PaginationArgs,
} from "./types";
// Resolvers define how to fetch the types defined in your schema.
// This resolver retrieves books from the "books" array above.
export const resolvers = {
Query: {
async user(_: unknown, args: { id: string }) {
return await getUser(args.id);
},
async resource(
_: unknown,
args: { id: string; userId: string },
): Promise<Resource> {
const maybeAcl = await queryResourceAcl({
userId: args.userId,
resourceId: args.id,
});
if (maybeAcl == null) {
throw new GraphQLError(
"The user doesn't have access to the given resource",
{
extensions: {
code: "FORBIDDEN",
},
},
);
}
const maybeResource = await getResource(args.id);
if (maybeResource == null) {
throw new GraphQLError("Resource not found", {
extensions: { code: "RESOURCE_NOT_FOUND" },
});
}
return maybeResource;
},
},
User: {
async resources(parent: UserRecord, args: PaginationArgs) {
return await getResources({ userId: parent.id, ...args });
},
},
Resource: {
async comments(
parent: Resource,
{ limit, cursor }: PaginationArgs,
): Promise<CommentCollection> {
return await getComments({
resourceId: parent.id,
limit,
cursor,
});
},
},
};
+37
View File
@@ -0,0 +1,37 @@
type Comment {
id: String!
content: String!
createdAt: Date!
userId: String!
}
type CommentCollection {
items: [Comment!]!
cursor: String
totalCount: Int!
}
type Resource {
id: String!
name: String!
createdAt: DateTime!
comments(limit: Int! = 10, cursor: String = null): CommentCollection!
}
type ResourceCollection {
items: [Resource!]!
cursor: String
totalCount: Int!
}
type User {
id: String!
name: String!
resources(limit: Int! = 10, cursor: String = null): ResourceCollection!
}
type Query {
user(id: String!): User
resource(id: String!, userId: String!): Resource
}
+61
View File
@@ -0,0 +1,61 @@
import {
queryUser,
queryResource,
countComments,
queryComments,
countResources,
queryResources,
} from "./repositories";
import {
UserRecord,
Resource,
CommentCollection,
PaginationArgs,
ResourceCollection,
} from "./types";
export const getUser = async (id: string): Promise<UserRecord | null> => {
return await queryUser(id);
};
export const getResource = async (id: string): Promise<Resource | null> => {
return await queryResource(id);
};
interface GetResourcesArgs extends PaginationArgs {
userId: string;
}
export const getResources = async (
params: GetResourcesArgs,
): Promise<ResourceCollection> => {
const totalCount = await countResources(params.userId);
const items = await queryResources(params);
let cursor = null;
if (items.length > 0) {
cursor = items.slice(-1)[0].createdAt.toISOString();
}
return {
totalCount,
items,
cursor,
};
};
export const getComments = async (params: {
resourceId: string;
limit: number;
cursor: string | null;
}): Promise<CommentCollection> => {
// yes, i should be doing base64 de and encoding with the cursor...
const totalCount = await countComments(params.resourceId);
const items = await queryComments(params);
let cursor = null;
if (items.length > 0) {
cursor = items.slice(-1)[0].createdAt.toISOString();
}
return {
totalCount,
items,
cursor,
};
};
+46
View File
@@ -0,0 +1,46 @@
export interface Comment {
id: string;
userId: string;
content: string;
createdAt: Date;
resourceId: string;
}
export interface PaginationArgs {
limit: number;
cursor: string | null;
}
interface Collection<T> {
totalCount: number;
cursor: string | null;
items: T[];
}
export interface CommentCollection extends Collection<Comment> {}
export interface Resource {
id: string;
name: string;
createdAt: Date;
}
export interface ResourceCollection extends Collection<Resource> {}
export interface UserRecord {
id: string;
name: string;
}
export interface User extends UserRecord {
resources: {
cursor: string | null;
totalCount: number;
items: Resource[];
};
}
export interface ResourceAcl {
userId: string;
resourceId: string;
}
+109
View File
@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}