-
-
Notifications
You must be signed in to change notification settings - Fork 24
API (wip) #1662
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
Draft
HugoGresse
wants to merge
17
commits into
main
Choose a base branch
from
api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
API (wip) #1662
Changes from 10 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
bcf7548
api-wip
HugoGresse 8fd97db
Merge branch 'main' into api
HugoGresse 534df22
WIP
HugoGresse 207fb9d
WIP on UT
HugoGresse bfb238a
Fix error logging
HugoGresse 5e8c8a7
Working unit test on organization !
HugoGresse f939902
Update TS and fix breaking changes in functions
HugoGresse d79ae88
Add user hydratation when getting an org
HugoGresse 3ebd440
Replace query paran by a header for auth
HugoGresse 9847e99
Migration functrion to v2, replace SwaggerUI by scalar
HugoGresse b8c62bc
Update build
HugoGresse 92e1e5d
Update vite/storybook/esbuild to attempt to fix build issue
HugoGresse b6ba35d
For esbuild v
HugoGresse 787ddff
Force esbuild on vitest
HugoGresse 1af0da1
Fix test
HugoGresse 31b8989
Dumb remove to showcase cypress-axe
HugoGresse 0d46074
Revert and remove hound
HugoGresse File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { FastifyInstance } from 'fastify' | ||
|
|
||
| export const addContentTypeParserForServerless = (fastify: FastifyInstance) => { | ||
| // For serverless compatibility | ||
| fastify.addContentTypeParser('application/json', {}, (req, body, done) => { | ||
| done(null, (body as any).body) | ||
| }) | ||
| fastify.addContentTypeParser( | ||
| 'multipart/form-data', | ||
| {}, | ||
| (req, body, done) => { | ||
| done(null, req) | ||
| } | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import Fastify from 'fastify' | ||
| import { addContentTypeParserForServerless } from './addContentTypeParserForServerless' | ||
| import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox' | ||
| import { App as FirebaseApp } from 'firebase-admin/app' | ||
| import { apiKeyPlugin } from './plugins/apiKeyPlugin' | ||
| import { firebasePlugin } from './plugins/firebasePlugin' | ||
| import cors from '@fastify/cors' | ||
| import { openAPIPlugin } from './plugins/openAPIPlugin' | ||
| import { fastifyErrorHandler } from './others/fastifyErrorHandler' | ||
| import { fastifyNotFoundHandler } from './others/fastifyNotFoundHandler' | ||
| import { organizationsRoutes } from './routes/organizations' | ||
|
|
||
| type Firebase = FirebaseApp | ||
| declare module 'fastify' { | ||
| interface FastifyInstance { | ||
| firebase: Firebase | ||
| } | ||
| } | ||
|
|
||
| export async function createFastifyAPI() { | ||
| const fastify = Fastify({ | ||
| logger: true, // always enable full log | ||
| }).withTypeProvider<TypeBoxTypeProvider>() | ||
| addContentTypeParserForServerless(fastify) | ||
|
|
||
| fastify.register(firebasePlugin) | ||
| fastify.register(apiKeyPlugin) | ||
| fastify.register(cors, { | ||
| origin: '*', | ||
| }) | ||
| fastify.register(openAPIPlugin) | ||
| fastify.setErrorHandler(fastifyErrorHandler) | ||
| fastify.setNotFoundHandler(fastifyNotFoundHandler) | ||
|
|
||
| fastify.addHook('onSend', (_, reply, _2, done: () => void) => { | ||
| reply.header('Cache-Control', 'must-revalidate,no-cache,no-store') | ||
| done() | ||
| }) | ||
|
|
||
| fastify.register(organizationsRoutes, { prefix: '/organizations' }) | ||
|
|
||
| return fastify | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { App as FirebaseApp } from 'firebase-admin/app' | ||
| import { getFirestore } from 'firebase-admin/firestore' | ||
| import { Organization, HydratedOrganization } from '../../types/Organization' | ||
| import { NotFoundError } from '../others/Errors' | ||
| import { APIKey } from '../plugins/APIKey' | ||
| import { UserDao } from './UserDao' | ||
| import { User } from '../../types/User' | ||
|
|
||
| const ORGANIZATION_COLLECTION = 'organizations' | ||
|
|
||
| export class OrganizationDao { | ||
| public static async getOrganizationFromId( | ||
| firebaseApp: FirebaseApp, | ||
| organizationId: string | ||
| ): Promise<Organization> { | ||
| const db = getFirestore(firebaseApp) | ||
| const organizationDoc = await db | ||
| .collection(ORGANIZATION_COLLECTION) | ||
| .doc(organizationId) | ||
| .get() | ||
|
|
||
| if (!organizationDoc.exists) { | ||
| throw new NotFoundError('Organization not found') | ||
| } | ||
|
|
||
| return { | ||
| id: organizationDoc.id, | ||
| ...organizationDoc.data(), | ||
| } as Organization | ||
| } | ||
|
|
||
| public static async getOrganizationFromApiKey( | ||
| firebaseApp: FirebaseApp, | ||
| apiKey: APIKey | ||
| ): Promise<Organization | null> { | ||
| const db = getFirestore(firebaseApp) | ||
|
|
||
| const doc = await db | ||
| .collection(ORGANIZATION_COLLECTION) | ||
| .where('apiKey', '==', apiKey.apiKey) | ||
| .get() | ||
|
|
||
| if (!doc || doc.empty || doc.docs.length === 0) { | ||
| throw new NotFoundError('Organization not found') | ||
| } | ||
|
|
||
| return { | ||
| id: doc.docs[0].id, | ||
| ...doc.docs[0].data(), | ||
| } as Organization | ||
| } | ||
|
|
||
| public static async hydrateOrganization( | ||
| firebaseApp: FirebaseApp, | ||
| organization: Organization | ||
| ): Promise<HydratedOrganization> { | ||
| const allUserIds = [ | ||
| organization.ownerUserId, | ||
| ...(organization.adminUserIds || []), | ||
| ...(organization.editorUserIds || []), | ||
| ...(organization.viewerUserIds || []), | ||
| ] | ||
|
|
||
| const usersMap = await UserDao.getUsersByIds(firebaseApp, allUserIds) | ||
|
|
||
| const getUser = (userId: string): User => { | ||
| return ( | ||
| usersMap.get(userId) || { | ||
| id: userId, | ||
| displayName: undefined, | ||
| email: undefined, | ||
| photoUrl: undefined, | ||
| createdAt: undefined, | ||
| updatedAt: undefined, | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| const { | ||
| ownerUserId, | ||
| adminUserIds, | ||
| editorUserIds, | ||
| viewerUserIds, | ||
| ...rest | ||
| } = organization | ||
|
|
||
| return { | ||
| ...rest, | ||
| ownerUser: getUser(ownerUserId), | ||
| adminUsers: (adminUserIds || []).map(getUser), | ||
| editorUsers: (editorUserIds || []).map(getUser), | ||
| viewerUsers: (viewerUserIds || []).map(getUser), | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { App as FirebaseApp } from 'firebase-admin/app' | ||
| import { getFirestore } from 'firebase-admin/firestore' | ||
| import { Project } from '../../types/Project' | ||
| import { NotFoundError } from '../others/Errors' | ||
| import { APIKey } from '../plugins/APIKey' | ||
|
|
||
| const PROJECT_COLLECTION = 'projects' | ||
|
|
||
| export class ProjectDao { | ||
| public static async getProjectFromId( | ||
| firebaseApp: FirebaseApp, | ||
| projectId: string | ||
| ): Promise<Project> { | ||
| const db = getFirestore(firebaseApp) | ||
| const doc = await db.collection(PROJECT_COLLECTION).doc(projectId).get() | ||
|
|
||
| if (!doc.exists) { | ||
| throw new NotFoundError('Project not found') | ||
| } | ||
|
|
||
| return { | ||
| id: doc.id, | ||
| ...doc.data(), | ||
| } as Project | ||
| } | ||
|
|
||
| public static async getProjectFromApiKey( | ||
| firebaseApp: FirebaseApp, | ||
| apiKey: APIKey | ||
| ): Promise<Project | null> { | ||
| const db = getFirestore(firebaseApp) | ||
| const doc = await db | ||
| .collection(PROJECT_COLLECTION) | ||
| .where('apiKey', '==', apiKey.apiKey) | ||
| .get() | ||
|
|
||
| if (!doc || doc.empty || doc.docs.length === 0) { | ||
| throw new NotFoundError('Project not found') | ||
| } | ||
|
|
||
| return { | ||
| id: doc.docs[0].id, | ||
| ...doc.docs[0].data(), | ||
| } as Project | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { App as FirebaseApp } from 'firebase-admin/app' | ||
| import { getFirestore } from 'firebase-admin/firestore' | ||
| import { User } from '../../types/User' | ||
|
|
||
| const USER_COLLECTION = 'users' | ||
|
|
||
| export class UserDao { | ||
| public static async getUsersByIds( | ||
| firebaseApp: FirebaseApp, | ||
| userIds: string[] | ||
| ): Promise<Map<string, User>> { | ||
| if (userIds.length === 0) { | ||
| return new Map() | ||
| } | ||
|
|
||
| const db = getFirestore(firebaseApp) | ||
| const uniqueUserIds = [...new Set(userIds)] | ||
|
|
||
| const userPromises = uniqueUserIds.map(async (userId) => { | ||
| try { | ||
| const userDoc = await db | ||
| .collection(USER_COLLECTION) | ||
| .doc(userId) | ||
| .get() | ||
|
|
||
| if (!userDoc.exists) { | ||
| return null | ||
| } | ||
|
|
||
| const data = userDoc.data() | ||
| return { | ||
| id: userDoc.id, | ||
| displayName: data?.displayName, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Parsing error: Expression expected |
||
| email: data?.email, | ||
| photoUrl: data?.photoURL || data?.photoUrl, | ||
| createdAt: | ||
| data?.createdAt?.toDate?.()?.toISOString() || | ||
| data?.createdAt, | ||
| updatedAt: | ||
| data?.updatedAt?.toDate?.()?.toISOString() || | ||
| data?.updatedAt, | ||
| } as User | ||
| } catch (error) { | ||
| return null | ||
| } | ||
| }) | ||
|
|
||
| const users = await Promise.all(userPromises) | ||
| const userMap = new Map<string, User>() | ||
|
|
||
| users.forEach((user) => { | ||
| if (user) { | ||
| userMap.set(user.id, user) | ||
| } | ||
| }) | ||
|
|
||
| return userMap | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export const isNodeEnvDev = process.env.NODE_ENV === 'development' | ||
| export const isNodeEnvTest = process.env.NODE_ENV === 'test' |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.