mirror of
https://github.com/Sonny93/my-links.git
synced 2025-12-09 07:03:25 +00:00
Compare commits
111 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d4eb08bc9 | ||
|
|
f8e7e7cd64 | ||
|
|
cda3a89f32 | ||
|
|
ed4dbca329 | ||
|
|
f8a92b7219 | ||
|
|
161db362b3 | ||
|
|
a5e542a33f | ||
|
|
f0ec6d6b3d | ||
|
|
442a1003bb | ||
|
|
2c499a7789 | ||
|
|
5baa9e1c35 | ||
|
|
fd896db872 | ||
|
|
a45d534fa0 | ||
|
|
5d083327a8 | ||
|
|
136fcfac5d | ||
|
|
efcb1d0ef9 | ||
|
|
8b9e74bfe1 | ||
|
|
73752aed32 | ||
|
|
16a4ce1761 | ||
|
|
049feab0d8 | ||
|
|
1da84e1afe | ||
|
|
de2cf5bd13 | ||
|
|
9e1dcbb07d | ||
|
|
493632e6db | ||
|
|
6b318e1acb | ||
|
|
d7381ed92a | ||
|
|
c20dd4651c | ||
|
|
8a4f895853 | ||
|
|
dc54a1197d | ||
|
|
09821de424 | ||
|
|
cdfd092489 | ||
|
|
8e1e3bea17 | ||
|
|
e9ccefd938 | ||
|
|
f2478bcf56 | ||
|
|
76847ff76b | ||
|
|
e03952de1c | ||
|
|
55cd973b1a | ||
|
|
202f70b010 | ||
|
|
f3f7f6272f | ||
|
|
14d051a9d6 | ||
|
|
8437f6b96d | ||
|
|
9481b0ad7d | ||
|
|
8b161dcf49 | ||
|
|
09700a1916 | ||
|
|
56c05f1bf6 | ||
|
|
b28499a69a | ||
|
|
31b4f22772 | ||
|
|
3ff7619e94 | ||
|
|
e6803c174c | ||
|
|
b7d80d844d | ||
|
|
50030df9a6 | ||
|
|
32133be8b0 | ||
|
|
2ba0eccc9f | ||
|
|
25d70f2faf | ||
|
|
3c2c5dcee6 | ||
|
|
8176817030 | ||
|
|
8077f8f9c9 | ||
|
|
a910b898c7 | ||
|
|
53aa7bc22b | ||
|
|
18b2eb2c5a | ||
|
|
57ed2c5e94 | ||
|
|
905f0ba1c7 | ||
|
|
19b96650e9 | ||
|
|
6b5aba6f84 | ||
|
|
6b4cfd9926 | ||
|
|
6b327a5b1e | ||
|
|
a58d78302e | ||
|
|
5a8bda0322 | ||
|
|
c916b5870b | ||
|
|
243984ca66 | ||
|
|
f0e64c19fd | ||
|
|
56aade5222 | ||
|
|
2f0e1dd375 | ||
|
|
0f1dc9b69c | ||
|
|
3531038321 | ||
|
|
b5cda75790 | ||
|
|
5f5eece627 | ||
|
|
817b9baafc | ||
|
|
73f8c0c513 | ||
|
|
2cf8c5ae02 | ||
|
|
2cc490b611 | ||
|
|
31f22d382e | ||
|
|
97044907ee | ||
|
|
602813ec05 | ||
|
|
e917b3ae2b | ||
|
|
a347cee9a7 | ||
|
|
231629f0dd | ||
|
|
08dcd7455f | ||
|
|
df4185bd62 | ||
|
|
2531242615 | ||
|
|
1386db6935 | ||
|
|
219e5e3aed | ||
|
|
4bc1a455a8 | ||
|
|
c78eac59fd | ||
|
|
3580eeccde | ||
|
|
7ed11fe4aa | ||
|
|
6b72af9e8f | ||
|
|
194b541143 | ||
|
|
f79baf21c0 | ||
|
|
1068b6e057 | ||
|
|
e30bdea9c5 | ||
|
|
f1a70f3bd1 | ||
|
|
a53b600111 | ||
|
|
78915b6b99 | ||
|
|
b59b948ed9 | ||
|
|
a317ee1b61 | ||
|
|
42a5dabec1 | ||
|
|
883b36c93e | ||
|
|
584489dbb9 | ||
|
|
cf6b87306e | ||
|
|
5a792aef13 |
@@ -1,8 +1,15 @@
|
|||||||
|
# Adonis default .gitignore ignores
|
||||||
node_modules
|
node_modules
|
||||||
.env
|
build
|
||||||
.next
|
coverage
|
||||||
.vscode
|
.vscode
|
||||||
example.env
|
.DS_STORE
|
||||||
|
.env
|
||||||
|
tmp
|
||||||
|
storage
|
||||||
|
|
||||||
|
# Additional .gitignore ignores (any custom file you wish)
|
||||||
|
.idea
|
||||||
|
|
||||||
# Additional good to have ignores for dockerignore
|
# Additional good to have ignores for dockerignore
|
||||||
Dockerfile*
|
Dockerfile*
|
||||||
@@ -11,3 +18,6 @@ docker-compose*
|
|||||||
*.md
|
*.md
|
||||||
.git
|
.git
|
||||||
.gitignore
|
.gitignore
|
||||||
|
|
||||||
|
# App specific
|
||||||
|
database/seeders
|
||||||
|
|||||||
@@ -1,10 +1,24 @@
|
|||||||
|
# http://editorconfig.org
|
||||||
|
|
||||||
root = true
|
root = true
|
||||||
|
|
||||||
[*]
|
[*]
|
||||||
charset = utf-8
|
|
||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
tab_width = 4
|
|
||||||
end_of_line = lf
|
end_of_line = lf
|
||||||
insert_final_newline = true
|
charset = utf-8
|
||||||
trim_trailing_whitespace = true
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
|
||||||
|
[*.json]
|
||||||
|
insert_final_newline = unset
|
||||||
|
|
||||||
|
[**.min.js]
|
||||||
|
indent_style = unset
|
||||||
|
insert_final_newline = unset
|
||||||
|
|
||||||
|
[MakeFile]
|
||||||
|
indent_style = space
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|||||||
16
.env.example
Normal file
16
.env.example
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# node ace generate:key
|
||||||
|
APP_KEY=soY8ZAtItT_fCkNUADfgffZUUo675lOj
|
||||||
|
TZ=UTC
|
||||||
|
PORT=3333
|
||||||
|
HOST=localhost
|
||||||
|
LOG_LEVEL=info
|
||||||
|
NODE_ENV=development
|
||||||
|
SESSION_DRIVER=cookie
|
||||||
|
DB_HOST=127.0.0.1
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASSWORD=my-links-pwd
|
||||||
|
DB_DATABASE=my-links
|
||||||
|
GOOGLE_CLIENT_ID=
|
||||||
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
GOOGLE_CLIENT_CALLBACK_URL=http://localhost:3333/auth/callback
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "next",
|
|
||||||
"rules": {
|
|
||||||
"react/no-unescaped-entities": "off"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
2
.gitattributes
vendored
2
.gitattributes
vendored
@@ -1,2 +0,0 @@
|
|||||||
# Auto detect text files and perform LF normalization
|
|
||||||
* text=auto
|
|
||||||
@@ -50,4 +50,4 @@ jobs:
|
|||||||
key: ${{ secrets.SSH_KEY }}
|
key: ${{ secrets.SSH_KEY }}
|
||||||
script: |
|
script: |
|
||||||
cd /infra/my-links
|
cd /infra/my-links
|
||||||
docker compose up -d
|
sh startup.sh
|
||||||
55
.gitignore
vendored
55
.gitignore
vendored
@@ -1,45 +1,24 @@
|
|||||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
# Dependencies and AdonisJS build
|
||||||
|
node_modules
|
||||||
|
build
|
||||||
|
tmp
|
||||||
|
|
||||||
# dependencies
|
# Secrets
|
||||||
/node_modules
|
|
||||||
/.pnp
|
|
||||||
.pnp.js
|
|
||||||
|
|
||||||
# testing
|
|
||||||
/coverage
|
|
||||||
|
|
||||||
# next.js
|
|
||||||
/.next/
|
|
||||||
/out/
|
|
||||||
|
|
||||||
# production
|
|
||||||
/build
|
|
||||||
|
|
||||||
# misc
|
|
||||||
.DS_Store
|
|
||||||
*.pem
|
|
||||||
.idea
|
|
||||||
.vscode
|
|
||||||
|
|
||||||
# debug
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
|
|
||||||
# local env files
|
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
.env.development.local
|
|
||||||
.env.test.local
|
|
||||||
.env.production.local
|
.env.production.local
|
||||||
|
.env.development.local
|
||||||
|
|
||||||
# vercel
|
# Frontend assets compiled code
|
||||||
.vercel
|
public/assets
|
||||||
|
|
||||||
# sitemap files (they are generated by postbuild script)
|
# Build tools specific
|
||||||
public/sitemap*
|
npm-debug.log
|
||||||
public/robots.txt
|
yarn-error.log
|
||||||
|
|
||||||
# pwa static files
|
# Editors specific
|
||||||
/public/sw*
|
.fleet
|
||||||
/public/workbox-*
|
.idea
|
||||||
|
|
||||||
|
# Platform specific
|
||||||
|
.DS_Store
|
||||||
|
|||||||
3
.husky/pre-commit
Executable file → Normal file
3
.husky/pre-commit
Executable file → Normal file
@@ -1,4 +1 @@
|
|||||||
#!/usr/bin/env sh
|
|
||||||
. "$(dirname -- "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
npx lint-staged
|
npx lint-staged
|
||||||
|
|||||||
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@@ -1,8 +0,0 @@
|
|||||||
# Default ignored files
|
|
||||||
/shelf/
|
|
||||||
/workspace.xml
|
|
||||||
# Editor-based HTTP Client requests
|
|
||||||
/httpRequests/
|
|
||||||
# Datasource local storage ignored files
|
|
||||||
/dataSources/
|
|
||||||
/dataSources.local.xml
|
|
||||||
63
.idea/codeStyles/Project.xml
generated
63
.idea/codeStyles/Project.xml
generated
@@ -1,63 +0,0 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
|
||||||
<code_scheme name="Project" version="173">
|
|
||||||
<HTMLCodeStyleSettings>
|
|
||||||
<option name="HTML_SPACE_INSIDE_EMPTY_TAG" value="true" />
|
|
||||||
<option name="HTML_QUOTE_STYLE" value="Single" />
|
|
||||||
<option name="HTML_ENFORCE_QUOTES" value="true" />
|
|
||||||
</HTMLCodeStyleSettings>
|
|
||||||
<JSCodeStyleSettings version="0">
|
|
||||||
<option name="FORCE_SEMICOLON_STYLE" value="true" />
|
|
||||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
|
||||||
<option name="USE_DOUBLE_QUOTES" value="false" />
|
|
||||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
|
||||||
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
|
|
||||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
|
||||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
|
||||||
</JSCodeStyleSettings>
|
|
||||||
<TypeScriptCodeStyleSettings version="0">
|
|
||||||
<option name="FORCE_SEMICOLON_STYLE" value="true" />
|
|
||||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
|
||||||
<option name="USE_DOUBLE_QUOTES" value="false" />
|
|
||||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
|
||||||
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
|
|
||||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
|
||||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
|
||||||
</TypeScriptCodeStyleSettings>
|
|
||||||
<VueCodeStyleSettings>
|
|
||||||
<option name="INTERPOLATION_NEW_LINE_AFTER_START_DELIMITER" value="false" />
|
|
||||||
<option name="INTERPOLATION_NEW_LINE_BEFORE_END_DELIMITER" value="false" />
|
|
||||||
</VueCodeStyleSettings>
|
|
||||||
<codeStyleSettings language="HTML">
|
|
||||||
<option name="SOFT_MARGINS" value="100" />
|
|
||||||
<indentOptions>
|
|
||||||
<option name="INDENT_SIZE" value="2" />
|
|
||||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
|
||||||
<option name="TAB_SIZE" value="2" />
|
|
||||||
</indentOptions>
|
|
||||||
</codeStyleSettings>
|
|
||||||
<codeStyleSettings language="JavaScript">
|
|
||||||
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
|
|
||||||
<option name="SOFT_MARGINS" value="100" />
|
|
||||||
<indentOptions>
|
|
||||||
<option name="INDENT_SIZE" value="2" />
|
|
||||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
|
||||||
<option name="TAB_SIZE" value="2" />
|
|
||||||
</indentOptions>
|
|
||||||
</codeStyleSettings>
|
|
||||||
<codeStyleSettings language="TypeScript">
|
|
||||||
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
|
|
||||||
<option name="SOFT_MARGINS" value="100" />
|
|
||||||
<indentOptions>
|
|
||||||
<option name="INDENT_SIZE" value="2" />
|
|
||||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
|
||||||
<option name="TAB_SIZE" value="2" />
|
|
||||||
</indentOptions>
|
|
||||||
</codeStyleSettings>
|
|
||||||
<codeStyleSettings language="Vue">
|
|
||||||
<option name="SOFT_MARGINS" value="100" />
|
|
||||||
<indentOptions>
|
|
||||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
|
||||||
</indentOptions>
|
|
||||||
</codeStyleSettings>
|
|
||||||
</code_scheme>
|
|
||||||
</component>
|
|
||||||
5
.idea/codeStyles/codeStyleConfig.xml
generated
5
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +0,0 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
|
||||||
<state>
|
|
||||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
|
||||||
</state>
|
|
||||||
</component>
|
|
||||||
5
.idea/misc.xml
generated
5
.idea/misc.xml
generated
@@ -1,5 +0,0 @@
|
|||||||
<project version="4">
|
|
||||||
<component name="ProjectRootManager">
|
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectModuleManager">
|
|
||||||
<modules>
|
|
||||||
<module fileurl="file://$PROJECT_DIR$/.idea/my-links.iml" filepath="$PROJECT_DIR$/.idea/my-links.iml" />
|
|
||||||
</modules>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
9
.idea/my-links.iml
generated
9
.idea/my-links.iml
generated
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<module type="JAVA_MODULE" version="4">
|
|
||||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
|
||||||
<exclude-output />
|
|
||||||
<content url="file://$MODULE_DIR$" />
|
|
||||||
<orderEntry type="inheritedJdk" />
|
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
|
||||||
</component>
|
|
||||||
</module>
|
|
||||||
7
.idea/prettier.xml
generated
7
.idea/prettier.xml
generated
@@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="PrettierConfiguration">
|
|
||||||
<option name="myConfigurationMode" value="AUTOMATIC" />
|
|
||||||
<option name="myRunOnSave" value="true" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="" vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
21
.prettierrc
21
.prettierrc
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"arrowParens": "always",
|
|
||||||
"bracketSameLine": false,
|
|
||||||
"bracketSpacing": true,
|
|
||||||
"semi": true,
|
|
||||||
"experimentalTernaries": false,
|
|
||||||
"singleQuote": true,
|
|
||||||
"jsxSingleQuote": true,
|
|
||||||
"quoteProps": "as-needed",
|
|
||||||
"trailingComma": "all",
|
|
||||||
"singleAttributePerLine": true,
|
|
||||||
"htmlWhitespaceSensitivity": "css",
|
|
||||||
"vueIndentScriptAndStyle": false,
|
|
||||||
"proseWrap": "preserve",
|
|
||||||
"insertPragma": false,
|
|
||||||
"printWidth": 80,
|
|
||||||
"requirePragma": false,
|
|
||||||
"tabWidth": 2,
|
|
||||||
"useTabs": false,
|
|
||||||
"embeddedLanguageFormatting": "auto"
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
{
|
{
|
||||||
"hooks": {
|
"hooks": {
|
||||||
"before:init": [
|
"before:init": [
|
||||||
"npm run lint"
|
"pnpm format",
|
||||||
|
"pnpm lint"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"git": {
|
"git": {
|
||||||
"commitMessage": "chore: release v${version}"
|
"commitMessage": "chore: release v${version}",
|
||||||
|
"commit": true,
|
||||||
|
"tag": true,
|
||||||
|
"push": true
|
||||||
},
|
},
|
||||||
"github": {
|
"github": {
|
||||||
"release": true
|
"release": true
|
||||||
|
|||||||
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"discord.enabled": false
|
"typescript.preferences.importModuleSpecifier": "non-relative"
|
||||||
}
|
}
|
||||||
|
|||||||
85
Dockerfile
85
Dockerfile
@@ -1,54 +1,61 @@
|
|||||||
# Source : https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile
|
# Source : https://github.com/adonisjs-community/adonis-packages/blob/main/Dockerfile
|
||||||
|
|
||||||
FROM node:18-alpine AS base
|
FROM node:20-alpine3.18 AS base
|
||||||
|
|
||||||
# Install dependencies only when needed
|
RUN apk --no-cache add curl
|
||||||
|
RUN corepack enable
|
||||||
|
|
||||||
|
# All deps stage
|
||||||
FROM base AS deps
|
FROM base AS deps
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
ADD package.json pnpm-lock.yaml ./
|
||||||
|
RUN pnpm install --ignore-scripts
|
||||||
|
|
||||||
# Install dependencies based on the preferred package manager
|
# Production only deps stage
|
||||||
COPY package.json package-lock.json* ./
|
FROM base AS production-deps
|
||||||
RUN npm pkg delete scripts.prepare
|
|
||||||
RUN npm ci --omit=dev
|
|
||||||
|
|
||||||
# Rebuild the source code only when needed
|
|
||||||
FROM base AS builder
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=deps /app/node_modules ./node_modules
|
ADD package.json pnpm-lock.yaml ./
|
||||||
COPY . .
|
RUN pnpm install --ignore-scripts
|
||||||
|
|
||||||
ENV NEXT_TELEMETRY_DISABLED 1
|
# Build stage
|
||||||
RUN npx prisma generate
|
FROM base AS build
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
# Production image, copy all the files and run next
|
|
||||||
FROM base AS runner
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
COPY --from=deps /app/node_modules /app/node_modules
|
||||||
|
ADD . .
|
||||||
|
|
||||||
ENV NODE_ENV production
|
ENV PORT=3333
|
||||||
ENV NEXT_TELEMETRY_DISABLED 1
|
ENV HOST=localhost
|
||||||
|
ENV LOG_LEVEL=info
|
||||||
|
ENV APP_KEY=sLoJth45JD1vcS8n92Y2JUd8w3OL4HQb
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV SESSION_DRIVER=cookie
|
||||||
|
ENV DB_HOST=127.0.0.1
|
||||||
|
ENV DB_PORT=5432
|
||||||
|
ENV DB_USER=db_user
|
||||||
|
ENV DB_PASSWORD=db_password
|
||||||
|
ENV DB_DATABASE=db_db
|
||||||
|
ENV GOOGLE_CLIENT_ID=client_id
|
||||||
|
ENV GOOGLE_CLIENT_SECRET=client_secret
|
||||||
|
ENV GOOGLE_CLIENT_CALLBACK_URL=http://localhost:3333/auth/callback
|
||||||
|
|
||||||
RUN addgroup --system --gid 1001 nodejs
|
RUN node ace izzy:routes
|
||||||
RUN adduser --system --uid 1001 nextjs
|
RUN node ace build
|
||||||
|
|
||||||
COPY --from=builder /app/public ./public
|
# Production stage
|
||||||
COPY --from=builder /app/prisma ./prisma
|
FROM base
|
||||||
|
|
||||||
# Set the correct permission for prerender cache
|
ENV NODE_ENV=production
|
||||||
RUN mkdir .next
|
ENV LOG_LEVEL=debug
|
||||||
RUN chown nextjs:nodejs .next
|
ENV CACHE_VIEWS=false
|
||||||
|
ENV SESSION_DRIVER=cookie
|
||||||
|
ENV PORT=$PORT
|
||||||
|
|
||||||
# Automatically leverage output traces to reduce image size
|
WORKDIR /app
|
||||||
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
COPY --from=production-deps /app/node_modules /app/node_modules
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
COPY --from=build /app/build /app
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
|
||||||
|
|
||||||
USER nextjs
|
# Expose port
|
||||||
|
EXPOSE $PORT
|
||||||
|
|
||||||
EXPOSE 3000
|
# Start app
|
||||||
|
CMD node bin/console.js migration:run --force && node bin/server.js
|
||||||
ENV PORT 3000
|
|
||||||
# set hostname to localhost
|
|
||||||
ENV HOSTNAME "0.0.0.0"
|
|
||||||
|
|
||||||
CMD npx prisma migrate deploy && node server.js
|
|
||||||
|
|||||||
29
Makefile
29
Makefile
@@ -1,14 +1,19 @@
|
|||||||
db:
|
dev:
|
||||||
docker compose -f dev.docker-compose.yml up -d --wait
|
@docker compose down
|
||||||
|
@docker compose -f dev.docker-compose.yml up -d --wait
|
||||||
dev: db
|
@node ace migration:fresh
|
||||||
npx prisma migrate deploy
|
@pnpm run dev
|
||||||
npx prisma generate
|
|
||||||
npm run dev
|
|
||||||
|
|
||||||
release:
|
|
||||||
npm run release
|
|
||||||
|
|
||||||
prod:
|
prod:
|
||||||
-docker network create mylinks_app
|
@docker compose -f dev.docker-compose.yml down
|
||||||
docker compose up -d --build --wait
|
@docker compose up -d --build --wait
|
||||||
|
|
||||||
|
seed:
|
||||||
|
@node ace db:seed
|
||||||
|
|
||||||
|
down:
|
||||||
|
@-docker compose down
|
||||||
|
@-docker compose -f dev.docker-compose.yml down
|
||||||
|
|
||||||
|
release:
|
||||||
|
@pnpm run release
|
||||||
|
|||||||
57
README.md
57
README.md
@@ -11,26 +11,49 @@ Copy `example.env` file as `.env` and edit the properties.
|
|||||||
cp example.env .env
|
cp example.env .env
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dev
|
## Development
|
||||||
|
|
||||||
Leave the `DATABASE_URL` property filled
|
### Docker
|
||||||
|
|
||||||
```
|
|
||||||
cd docker
|
|
||||||
make start-dev
|
|
||||||
cd ..
|
|
||||||
npx prisma db push
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Prod
|
|
||||||
|
|
||||||
If you want to use your own database leave, the `DATABASE_URL` property filled in `docker/docker-compose.yml` with your database credentials, otherwise you'll have to delete it.
|
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
cd docker
|
make dev
|
||||||
make build
|
```
|
||||||
make start-prod
|
|
||||||
|
### PNPM
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# reset database and (force) apply all migrations
|
||||||
|
node ace migration:fresh
|
||||||
|
# start dev server
|
||||||
|
pnpm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Start as prod
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
```shell
|
||||||
|
make prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### PNPM
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# create production build
|
||||||
|
pnpm run build
|
||||||
|
# go to the build folder
|
||||||
|
cd build
|
||||||
|
# clone your .env
|
||||||
|
cp ../.env .
|
||||||
|
# then start the production build
|
||||||
|
pnpm run start
|
||||||
|
```
|
||||||
|
|
||||||
|
## Generate app_key
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# generate a random app key
|
||||||
|
openssl rand -base64 32
|
||||||
```
|
```
|
||||||
|
|
||||||
## GitHub Actions
|
## GitHub Actions
|
||||||
|
|||||||
27
ace.js
Normal file
27
ace.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| JavaScript entrypoint for running ace commands
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| DO NOT MODIFY THIS FILE AS IT WILL BE OVERRIDDEN DURING THE BUILD
|
||||||
|
| PROCESS.
|
||||||
|
|
|
||||||
|
| See docs.adonisjs.com/guides/typescript-build-process#creating-production-build
|
||||||
|
|
|
||||||
|
| Since, we cannot run TypeScript source code using "node" binary, we need
|
||||||
|
| a JavaScript entrypoint to run ace commands.
|
||||||
|
|
|
||||||
|
| This file registers the "ts-node/esm" hook with the Node.js module system
|
||||||
|
| and then imports the "bin/console.ts" file.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register hook to process TypeScript files using ts-node
|
||||||
|
*/
|
||||||
|
import 'ts-node-maintained/register/esm';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import ace console entrypoint
|
||||||
|
*/
|
||||||
|
await import('./bin/console.js');
|
||||||
110
adonisrc.ts
Normal file
110
adonisrc.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/core/app';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Commands
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| List of ace commands to register from packages. The application commands
|
||||||
|
| will be scanned automatically from the "./commands" directory.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
commands: [
|
||||||
|
() => import('@adonisjs/core/commands'),
|
||||||
|
() => import('@adonisjs/lucid/commands'),
|
||||||
|
() => import('@izzyjs/route/commands'),
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Service providers
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| List of service providers to import and register when booting the
|
||||||
|
| application
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
providers: [
|
||||||
|
() => import('@adonisjs/core/providers/app_provider'),
|
||||||
|
() => import('@adonisjs/core/providers/hash_provider'),
|
||||||
|
{
|
||||||
|
file: () => import('@adonisjs/core/providers/repl_provider'),
|
||||||
|
environment: ['repl', 'test'],
|
||||||
|
},
|
||||||
|
() => import('@adonisjs/core/providers/vinejs_provider'),
|
||||||
|
() => import('@adonisjs/core/providers/edge_provider'),
|
||||||
|
() => import('@adonisjs/session/session_provider'),
|
||||||
|
() => import('@adonisjs/vite/vite_provider'),
|
||||||
|
() => import('@adonisjs/shield/shield_provider'),
|
||||||
|
() => import('@adonisjs/static/static_provider'),
|
||||||
|
() => import('@adonisjs/cors/cors_provider'),
|
||||||
|
() => import('@adonisjs/lucid/database_provider'),
|
||||||
|
() => import('@adonisjs/auth/auth_provider'),
|
||||||
|
() => import('@adonisjs/inertia/inertia_provider'),
|
||||||
|
() => import('@adonisjs/ally/ally_provider'),
|
||||||
|
() => import('@izzyjs/route/izzy_provider'),
|
||||||
|
() => import('#providers/route_provider'),
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Preloads
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| List of modules to import before starting the application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
preloads: [() => import('#start/routes'), () => import('#start/kernel')],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Tests
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| List of test suites to organize tests by their type. Feel free to remove
|
||||||
|
| and add additional suites.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
tests: {
|
||||||
|
suites: [
|
||||||
|
{
|
||||||
|
files: ['tests/unit/**/*.spec(.ts|.js)'],
|
||||||
|
name: 'unit',
|
||||||
|
timeout: 2000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['tests/functional/**/*.spec(.ts|.js)'],
|
||||||
|
name: 'functional',
|
||||||
|
timeout: 30000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
forceExit: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Metafiles
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| A collection of files you want to copy to the build folder when creating
|
||||||
|
| the production build.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
metaFiles: [
|
||||||
|
{
|
||||||
|
pattern: 'resources/views/**/*.edge',
|
||||||
|
reloadServer: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pattern: 'public/**',
|
||||||
|
reloadServer: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
|
||||||
|
assetsBundler: false,
|
||||||
|
unstable_assembler: {
|
||||||
|
onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
|
||||||
|
onDevServerStarted: [() => import('@izzyjs/route/dev_hook')],
|
||||||
|
},
|
||||||
|
});
|
||||||
19
app/constants/keys.ts
Normal file
19
app/constants/keys.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const OPEN_SEARCH_KEY = 's';
|
||||||
|
const ESCAPE_KEY = 'escape';
|
||||||
|
|
||||||
|
const OPEN_CREATE_LINK_KEY = 'l';
|
||||||
|
const OPEN_CREATE_COLLECTION_KEY = 'c';
|
||||||
|
|
||||||
|
const ARROW_UP = 'ArrowUp';
|
||||||
|
const ARROW_DOWN = 'ArrowDown';
|
||||||
|
|
||||||
|
const KEYS = {
|
||||||
|
ARROW_DOWN,
|
||||||
|
ARROW_UP,
|
||||||
|
ESCAPE_KEY,
|
||||||
|
OPEN_CREATE_COLLECTION_KEY,
|
||||||
|
OPEN_CREATE_LINK_KEY,
|
||||||
|
OPEN_SEARCH_KEY,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default KEYS;
|
||||||
8
app/constants/paths.ts
Normal file
8
app/constants/paths.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
const PATHS = {
|
||||||
|
AUTHOR: 'https://www.sonny.dev/',
|
||||||
|
REPO_GITHUB: 'https://github.com/Sonny93/my-links',
|
||||||
|
EXTENSION:
|
||||||
|
'https://chromewebstore.google.com/detail/mylinks/agkmlplihacolkakgeccnbhphnepphma',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export default PATHS;
|
||||||
2
app/constants/session.ts
Normal file
2
app/constants/session.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export const PREFER_DARK_THEME = 'prefer_dark_theme';
|
||||||
|
export const DARK_THEME_DEFAULT_VALUE = true;
|
||||||
46
app/controllers/admin_controller.ts
Normal file
46
app/controllers/admin_controller.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import CollectionsController from '#controllers/collections_controller';
|
||||||
|
import LinksController from '#controllers/links_controller';
|
||||||
|
import UsersController from '#controllers/users_controller';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
class UserWithRelationCountDto {
|
||||||
|
constructor(private user: User) {}
|
||||||
|
|
||||||
|
toJson = () => ({
|
||||||
|
id: this.user.id,
|
||||||
|
email: this.user.email,
|
||||||
|
fullname: this.user.name,
|
||||||
|
avatarUrl: this.user.avatarUrl,
|
||||||
|
isAdmin: this.user.isAdmin,
|
||||||
|
createdAt: this.user.createdAt,
|
||||||
|
updatedAt: this.user.updatedAt,
|
||||||
|
count: {
|
||||||
|
link: Number(this.user.$extras.totalLinks),
|
||||||
|
collection: Number(this.user.$extras.totalCollections),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class AdminController {
|
||||||
|
constructor(
|
||||||
|
protected usersController: UsersController,
|
||||||
|
protected linksController: LinksController,
|
||||||
|
protected collectionsController: CollectionsController
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async index({ inertia }: HttpContext) {
|
||||||
|
const users = await this.usersController.getAllUsersWithTotalRelations();
|
||||||
|
const linksCount = await this.linksController.getTotalLinksCount();
|
||||||
|
const collectionsCount =
|
||||||
|
await this.collectionsController.getTotalCollectionsCount();
|
||||||
|
|
||||||
|
return inertia.render('admin/dashboard', {
|
||||||
|
users: users.map((user) => new UserWithRelationCountDto(user).toJson()),
|
||||||
|
totalLinks: linksCount,
|
||||||
|
totalCollections: collectionsCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
13
app/controllers/apps_controller.ts
Normal file
13
app/controllers/apps_controller.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { PREFER_DARK_THEME } from '#constants/session';
|
||||||
|
import { updateUserThemeValidator } from '#validators/user';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
export default class AppsController {
|
||||||
|
async updateUserTheme({ request, session, response }: HttpContext) {
|
||||||
|
const { preferDarkTheme } = await request.validateUsing(
|
||||||
|
updateUserThemeValidator
|
||||||
|
);
|
||||||
|
session.put(PREFER_DARK_THEME, preferDarkTheme);
|
||||||
|
return response.ok({ message: 'ok' });
|
||||||
|
}
|
||||||
|
}
|
||||||
141
app/controllers/collections_controller.ts
Normal file
141
app/controllers/collections_controller.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import Collection from '#models/collection';
|
||||||
|
import User from '#models/user';
|
||||||
|
import {
|
||||||
|
createCollectionValidator,
|
||||||
|
deleteCollectionValidator,
|
||||||
|
updateCollectionValidator,
|
||||||
|
} from '#validators/collection';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
|
export default class CollectionsController {
|
||||||
|
// Dashboard
|
||||||
|
async index({ auth, inertia, request, response }: HttpContext) {
|
||||||
|
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
|
||||||
|
if (collections.length === 0) {
|
||||||
|
return response.redirectToNamedRoute('collection.create-form');
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeCollectionId = Number(request.qs()?.collectionId ?? '');
|
||||||
|
const activeCollection = collections.find(
|
||||||
|
(c) => c.id === activeCollectionId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!activeCollection && !!activeCollectionId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
return inertia.render('dashboard', {
|
||||||
|
collections,
|
||||||
|
activeCollection: activeCollection || collections[0],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create collection form
|
||||||
|
async showCreatePage({ inertia, auth }: HttpContext) {
|
||||||
|
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
|
||||||
|
return inertia.render('collections/create', {
|
||||||
|
disableHomeLink: collections.length === 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method called when creating a collection
|
||||||
|
async store({ request, response, auth }: HttpContext) {
|
||||||
|
const payload = await request.validateUsing(createCollectionValidator);
|
||||||
|
const collection = await Collection.create({
|
||||||
|
...payload,
|
||||||
|
authorId: auth.user?.id!,
|
||||||
|
});
|
||||||
|
return this.redirectToCollectionId(response, collection.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async showEditPage({ auth, request, inertia, response }: HttpContext) {
|
||||||
|
const collectionId = request.qs()?.collectionId;
|
||||||
|
if (!collectionId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const collection = await this.getCollectionById(
|
||||||
|
collectionId,
|
||||||
|
auth.user!.id
|
||||||
|
);
|
||||||
|
return inertia.render('collections/edit', {
|
||||||
|
collection,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async update({ request, auth, response }: HttpContext) {
|
||||||
|
const { params, ...payload } = await request.validateUsing(
|
||||||
|
updateCollectionValidator
|
||||||
|
);
|
||||||
|
|
||||||
|
// Cant use validator (vinejs) custom rule 'cause its too generic,
|
||||||
|
// because we have to find a collection by identifier and
|
||||||
|
// check whether the current user is the author.
|
||||||
|
// https://vinejs.dev/docs/extend/custom_rules
|
||||||
|
await this.getCollectionById(params.id, auth.user!.id);
|
||||||
|
|
||||||
|
await Collection.updateOrCreate(
|
||||||
|
{
|
||||||
|
id: params.id,
|
||||||
|
},
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
return this.redirectToCollectionId(response, params.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async showDeletePage({ auth, request, inertia, response }: HttpContext) {
|
||||||
|
const collectionId = request.qs()?.collectionId;
|
||||||
|
if (!collectionId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const collection = await this.getCollectionById(
|
||||||
|
collectionId,
|
||||||
|
auth.user!.id
|
||||||
|
);
|
||||||
|
return inertia.render('collections/delete', {
|
||||||
|
collection,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete({ request, auth, response }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteCollectionValidator);
|
||||||
|
const collection = await this.getCollectionById(params.id, auth.user!.id);
|
||||||
|
await collection.delete();
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTotalCollectionsCount() {
|
||||||
|
const totalCount = await db.from('collections').count('* as total');
|
||||||
|
return Number(totalCount[0].total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get collection by id.
|
||||||
|
*
|
||||||
|
* /!\ Only return private collection (create by the current user)
|
||||||
|
*/
|
||||||
|
async getCollectionById(id: Collection['id'], userId: User['id']) {
|
||||||
|
return await Collection.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', userId)
|
||||||
|
.firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCollectionsByAuthorId(authorId: User['id']) {
|
||||||
|
return await Collection.query()
|
||||||
|
.where('author_id', authorId)
|
||||||
|
.orderBy('created_at')
|
||||||
|
.preload('links');
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectToCollectionId(
|
||||||
|
response: HttpContext['response'],
|
||||||
|
collectionId: Collection['id']
|
||||||
|
) {
|
||||||
|
return response.redirectToNamedRoute('dashboard', {
|
||||||
|
qs: { collectionId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
160
app/controllers/favicons_controller.ts
Normal file
160
app/controllers/favicons_controller.ts
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
import FaviconNotFoundException from '#exceptions/favicon_not_found_exception';
|
||||||
|
import { cache } from '#lib/cache';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
import { parse } from 'node-html-parser';
|
||||||
|
|
||||||
|
interface Favicon {
|
||||||
|
buffer: Buffer;
|
||||||
|
url: string;
|
||||||
|
type: string;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class FaviconsController {
|
||||||
|
private userAgent =
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0';
|
||||||
|
private relList = [
|
||||||
|
'icon',
|
||||||
|
'shortcut icon',
|
||||||
|
'apple-touch-icon',
|
||||||
|
'apple-touch-icon-precomposed',
|
||||||
|
'apple-touch-startup-image',
|
||||||
|
'mask-icon',
|
||||||
|
'fluid-icon',
|
||||||
|
];
|
||||||
|
|
||||||
|
async index(ctx: HttpContext) {
|
||||||
|
const url = ctx.request.qs()?.url;
|
||||||
|
if (!url) {
|
||||||
|
throw new Error('Missing URL');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheNs = cache.namespace('favicon');
|
||||||
|
const favicon = await cacheNs.getOrSet({
|
||||||
|
key: url,
|
||||||
|
ttl: '1h',
|
||||||
|
factory: () => this.tryGetFavicon(url),
|
||||||
|
});
|
||||||
|
return this.sendImage(ctx, favicon);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async tryGetFavicon(url: string): Promise<Favicon> {
|
||||||
|
const faviconUrl = this.buildFaviconUrl(url, '/favicon.ico');
|
||||||
|
try {
|
||||||
|
return await this.fetchFavicon(faviconUrl);
|
||||||
|
} catch {
|
||||||
|
logger.debug(`Unable to retrieve favicon from ${faviconUrl}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const documentText = await this.fetchDocumentText(url);
|
||||||
|
const faviconPath = this.extractFaviconPath(documentText);
|
||||||
|
|
||||||
|
if (!faviconPath) {
|
||||||
|
throw new FaviconNotFoundException(`No favicon path found in ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (faviconPath.startsWith('http')) {
|
||||||
|
try {
|
||||||
|
return await this.fetchFavicon(faviconPath);
|
||||||
|
} catch {
|
||||||
|
logger.debug(`Unable to retrieve favicon from ${faviconPath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.fetchFaviconFromPath(url, faviconPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchFavicon(url: string): Promise<Favicon> {
|
||||||
|
const response = await this.fetchWithUserAgent(url);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new FaviconNotFoundException(`Request to favicon ${url} failed`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = await response.blob();
|
||||||
|
if (!this.isImage(blob.type) || blob.size === 0) {
|
||||||
|
throw new FaviconNotFoundException(`Invalid image at ${url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
buffer: Buffer.from(await blob.arrayBuffer()),
|
||||||
|
url: response.url,
|
||||||
|
type: blob.type,
|
||||||
|
size: blob.size,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchDocumentText(url: string): Promise<string> {
|
||||||
|
const response = await this.fetchWithUserAgent(url);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new FaviconNotFoundException(`Request to ${url} failed`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractFaviconPath(html: string): string | undefined {
|
||||||
|
const document = parse(html);
|
||||||
|
const link = document
|
||||||
|
.getElementsByTagName('link')
|
||||||
|
.find((element) => this.relList.includes(element.getAttribute('rel')!));
|
||||||
|
return link?.getAttribute('href');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchFaviconFromPath(
|
||||||
|
baseUrl: string,
|
||||||
|
path: string
|
||||||
|
): Promise<Favicon> {
|
||||||
|
if (this.isBase64Image(path)) {
|
||||||
|
const buffer = this.convertBase64ToBuffer(path);
|
||||||
|
return {
|
||||||
|
buffer,
|
||||||
|
type: 'image/x-icon',
|
||||||
|
size: buffer.length,
|
||||||
|
url: path,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const faviconUrl = this.buildFaviconUrl(baseUrl, path);
|
||||||
|
return this.fetchFavicon(faviconUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildFaviconUrl(base: string, path: string): string {
|
||||||
|
const { origin } = new URL(base);
|
||||||
|
if (path.startsWith('/')) {
|
||||||
|
return origin + path;
|
||||||
|
}
|
||||||
|
|
||||||
|
const basePath = this.urlWithoutSearchParams(base);
|
||||||
|
const baseUrl = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
|
||||||
|
return `${baseUrl}/${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private urlWithoutSearchParams(url: string): string {
|
||||||
|
const { protocol, host, pathname } = new URL(url);
|
||||||
|
return `${protocol}//${host}${pathname}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isImage(type: string): boolean {
|
||||||
|
return type.startsWith('image/');
|
||||||
|
}
|
||||||
|
|
||||||
|
private isBase64Image(data: string): boolean {
|
||||||
|
return data.startsWith('data:image/');
|
||||||
|
}
|
||||||
|
|
||||||
|
private convertBase64ToBuffer(base64: string): Buffer {
|
||||||
|
return Buffer.from(base64.split(',')[1], 'base64');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchWithUserAgent(url: string): Promise<Response> {
|
||||||
|
const headers = new Headers({ 'User-Agent': this.userAgent });
|
||||||
|
return fetch(url, { headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendImage(ctx: HttpContext, { buffer, type, size }: Favicon) {
|
||||||
|
ctx.response.header('Content-Type', type);
|
||||||
|
ctx.response.header('Content-Length', size.toString());
|
||||||
|
ctx.response.send(buffer, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
131
app/controllers/links_controller.ts
Normal file
131
app/controllers/links_controller.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import CollectionsController from '#controllers/collections_controller';
|
||||||
|
import Link from '#models/link';
|
||||||
|
import {
|
||||||
|
createLinkValidator,
|
||||||
|
deleteLinkValidator,
|
||||||
|
updateLinkFavoriteStatusValidator,
|
||||||
|
updateLinkValidator,
|
||||||
|
} from '#validators/link';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class LinksController {
|
||||||
|
constructor(protected collectionsController: CollectionsController) {}
|
||||||
|
|
||||||
|
async showCreatePage({ auth, inertia }: HttpContext) {
|
||||||
|
const collections =
|
||||||
|
await this.collectionsController.getCollectionsByAuthorId(auth.user!.id);
|
||||||
|
return inertia.render('links/create', { collections });
|
||||||
|
}
|
||||||
|
|
||||||
|
async store({ auth, request, response }: HttpContext) {
|
||||||
|
const { collectionId, ...payload } =
|
||||||
|
await request.validateUsing(createLinkValidator);
|
||||||
|
|
||||||
|
await this.collectionsController.getCollectionById(
|
||||||
|
collectionId,
|
||||||
|
auth.user!.id
|
||||||
|
);
|
||||||
|
await Link.create({
|
||||||
|
...payload,
|
||||||
|
collectionId,
|
||||||
|
authorId: auth.user?.id!,
|
||||||
|
});
|
||||||
|
return this.collectionsController.redirectToCollectionId(
|
||||||
|
response,
|
||||||
|
collectionId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async showEditPage({ auth, inertia, request, response }: HttpContext) {
|
||||||
|
const linkId = request.qs()?.linkId;
|
||||||
|
if (!linkId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = auth.user!.id;
|
||||||
|
const collections =
|
||||||
|
await this.collectionsController.getCollectionsByAuthorId(userId);
|
||||||
|
const link = await this.getLinkById(linkId, userId);
|
||||||
|
|
||||||
|
return inertia.render('links/edit', { collections, link });
|
||||||
|
}
|
||||||
|
|
||||||
|
async update({ request, auth, response }: HttpContext) {
|
||||||
|
const { params, ...payload } =
|
||||||
|
await request.validateUsing(updateLinkValidator);
|
||||||
|
|
||||||
|
// Throw if invalid link id provided
|
||||||
|
await this.getLinkById(params.id, auth.user!.id);
|
||||||
|
|
||||||
|
await Link.updateOrCreate(
|
||||||
|
{
|
||||||
|
id: params.id,
|
||||||
|
},
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.redirectToNamedRoute('dashboard', {
|
||||||
|
qs: { collectionId: payload.collectionId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async toggleFavorite({ request, auth, response }: HttpContext) {
|
||||||
|
const { params, favorite } = await request.validateUsing(
|
||||||
|
updateLinkFavoriteStatusValidator
|
||||||
|
);
|
||||||
|
|
||||||
|
// Throw if invalid link id provided
|
||||||
|
await this.getLinkById(params.id, auth.user!.id);
|
||||||
|
|
||||||
|
await Link.updateOrCreate(
|
||||||
|
{
|
||||||
|
id: params.id,
|
||||||
|
},
|
||||||
|
{ favorite }
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.json({ status: 'ok' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async showDeletePage({ auth, inertia, request, response }: HttpContext) {
|
||||||
|
const linkId = request.qs()?.linkId;
|
||||||
|
if (!linkId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = await this.getLinkById(linkId, auth.user!.id);
|
||||||
|
await link.load('collection');
|
||||||
|
return inertia.render('links/delete', { link });
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete({ request, auth, response }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteLinkValidator);
|
||||||
|
|
||||||
|
const link = await this.getLinkById(params.id, auth.user!.id);
|
||||||
|
await link.delete();
|
||||||
|
|
||||||
|
return response.redirectToNamedRoute('dashboard', {
|
||||||
|
qs: { collectionId: link.id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTotalLinksCount() {
|
||||||
|
const totalCount = await db.from('links').count('* as total');
|
||||||
|
return Number(totalCount[0].total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get link by id.
|
||||||
|
*
|
||||||
|
* /!\ Only return private link (create by the current user)
|
||||||
|
*/
|
||||||
|
private async getLinkById(id: Link['id'], userId: Link['id']) {
|
||||||
|
return await Link.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', userId)
|
||||||
|
.firstOrFail();
|
||||||
|
}
|
||||||
|
}
|
||||||
18
app/controllers/searches_controller.ts
Normal file
18
app/controllers/searches_controller.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
|
export default class SearchesController {
|
||||||
|
async search({ request, auth }: HttpContext) {
|
||||||
|
const term = request.qs()?.term;
|
||||||
|
if (!term) {
|
||||||
|
console.warn('qs term null');
|
||||||
|
return { error: 'missing "term" query param' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { rows } = await db.rawQuery('SELECT * FROM search_text(?, ?)', [
|
||||||
|
term,
|
||||||
|
auth.user!.id,
|
||||||
|
]);
|
||||||
|
return { results: rows };
|
||||||
|
}
|
||||||
|
}
|
||||||
24
app/controllers/shared_collections_controller.ts
Normal file
24
app/controllers/shared_collections_controller.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { Visibility } from '#enums/visibility';
|
||||||
|
import Collection from '#models/collection';
|
||||||
|
import { getSharedCollectionValidator } from '#validators/shared_collection';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
export default class SharedCollectionsController {
|
||||||
|
async index({ request, inertia }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(
|
||||||
|
getSharedCollectionValidator
|
||||||
|
);
|
||||||
|
|
||||||
|
const collection = await this.getSharedCollectionById(params.id);
|
||||||
|
return inertia.render('shared', { collection });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getSharedCollectionById(id: Collection['id']) {
|
||||||
|
return await Collection.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('visibility', Visibility.PUBLIC)
|
||||||
|
.preload('links')
|
||||||
|
.preload('author')
|
||||||
|
.firstOrFail();
|
||||||
|
}
|
||||||
|
}
|
||||||
78
app/controllers/users_controller.ts
Normal file
78
app/controllers/users_controller.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import User from '#models/user';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
import { RouteName } from '@izzyjs/route/types';
|
||||||
|
|
||||||
|
export default class UsersController {
|
||||||
|
private redirectTo: RouteName = 'auth.login';
|
||||||
|
|
||||||
|
login({ inertia }: HttpContext) {
|
||||||
|
return inertia.render('login');
|
||||||
|
}
|
||||||
|
|
||||||
|
google = ({ ally }: HttpContext) => ally.use('google').redirect();
|
||||||
|
|
||||||
|
async callbackAuth({ ally, auth, response, session }: HttpContext) {
|
||||||
|
const google = ally.use('google');
|
||||||
|
if (google.accessDenied()) {
|
||||||
|
// TODO: translate error messages + show them in UI
|
||||||
|
session.flash('flash', 'Access was denied');
|
||||||
|
return response.redirectToNamedRoute(this.redirectTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (google.stateMisMatch()) {
|
||||||
|
session.flash('flash', 'Request expired. Retry again');
|
||||||
|
return response.redirectToNamedRoute(this.redirectTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (google.hasError()) {
|
||||||
|
session.flash('flash', google.getError() || 'Something went wrong');
|
||||||
|
return response.redirectToNamedRoute(this.redirectTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userCount = await db.from('users').count('* as total');
|
||||||
|
const {
|
||||||
|
email,
|
||||||
|
id: providerId,
|
||||||
|
name,
|
||||||
|
nickName,
|
||||||
|
avatarUrl,
|
||||||
|
token,
|
||||||
|
} = await google.user();
|
||||||
|
const user = await User.updateOrCreate(
|
||||||
|
{
|
||||||
|
email,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
email,
|
||||||
|
providerId,
|
||||||
|
name,
|
||||||
|
nickName,
|
||||||
|
avatarUrl,
|
||||||
|
token,
|
||||||
|
providerType: 'google',
|
||||||
|
isAdmin: userCount[0].total === '0' ? true : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await auth.use('web').login(user);
|
||||||
|
session.flash('flash', 'Successfully authenticated');
|
||||||
|
logger.info(`[${user.email}] auth success`);
|
||||||
|
|
||||||
|
response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
async logout({ auth, response, session }: HttpContext) {
|
||||||
|
await auth.use('web').logout();
|
||||||
|
session.flash('flash', 'Successfully disconnected');
|
||||||
|
logger.info(`[${auth.user?.email}] disconnected successfully`);
|
||||||
|
response.redirectToNamedRoute(this.redirectTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllUsersWithTotalRelations() {
|
||||||
|
return User.query()
|
||||||
|
.withCount('collections', (q) => q.as('totalCollections'))
|
||||||
|
.withCount('links', (q) => q.as('totalLinks'));
|
||||||
|
}
|
||||||
|
}
|
||||||
4
app/enums/visibility.ts
Normal file
4
app/enums/visibility.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export enum Visibility {
|
||||||
|
PUBLIC = 'PUBLIC',
|
||||||
|
PRIVATE = 'PRIVATE',
|
||||||
|
}
|
||||||
20
app/exceptions/favicon_not_found_exception.ts
Normal file
20
app/exceptions/favicon_not_found_exception.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Exception } from '@adonisjs/core/exceptions';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
import { createReadStream } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
export default class FaviconNotFoundException extends Exception {
|
||||||
|
static status = 404;
|
||||||
|
static code = 'E_FAVICON_NOT_FOUND';
|
||||||
|
|
||||||
|
async handle(error: this, ctx: HttpContext) {
|
||||||
|
const readStream = createReadStream(
|
||||||
|
resolve(process.cwd(), './public/empty-image.png')
|
||||||
|
);
|
||||||
|
|
||||||
|
ctx.response.header('Content-Type', 'image/png');
|
||||||
|
ctx.response.stream(readStream);
|
||||||
|
logger.debug(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
54
app/exceptions/handler.ts
Normal file
54
app/exceptions/handler.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { ExceptionHandler, HttpContext } from '@adonisjs/core/http';
|
||||||
|
import app from '@adonisjs/core/services/app';
|
||||||
|
import type {
|
||||||
|
StatusPageRange,
|
||||||
|
StatusPageRenderer,
|
||||||
|
} from '@adonisjs/core/types/http';
|
||||||
|
import { errors } from '@adonisjs/lucid';
|
||||||
|
|
||||||
|
export default class HttpExceptionHandler extends ExceptionHandler {
|
||||||
|
/**
|
||||||
|
* In debug mode, the exception handler will display verbose errors
|
||||||
|
* with pretty printed stack traces.
|
||||||
|
*/
|
||||||
|
protected debug = !app.inProduction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Status pages are used to display a custom HTML pages for certain error
|
||||||
|
* codes. You might want to enable them in production only, but feel
|
||||||
|
* free to enable them in development as well.
|
||||||
|
*/
|
||||||
|
protected renderStatusPages = app.inProduction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Status pages is a collection of error code range and a callback
|
||||||
|
* to return the HTML contents to send as a response.
|
||||||
|
*/
|
||||||
|
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
|
||||||
|
'404': (error, { inertia }) =>
|
||||||
|
inertia.render('errors/not_found', { error }),
|
||||||
|
'500..599': (error, { inertia }) =>
|
||||||
|
inertia.render('errors/server_error', { error }),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The method is used for handling errors and returning
|
||||||
|
* response to the client
|
||||||
|
*/
|
||||||
|
async handle(error: unknown, ctx: HttpContext) {
|
||||||
|
if (error instanceof errors.E_ROW_NOT_FOUND) {
|
||||||
|
return ctx.response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
return super.handle(error, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The method is used to report error to the logging service or
|
||||||
|
* the a third party error monitoring service.
|
||||||
|
*
|
||||||
|
* @note You should not attempt to send a response from this method.
|
||||||
|
*/
|
||||||
|
async report(error: unknown, ctx: HttpContext) {
|
||||||
|
return super.report(error, ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
10
app/lib/cache.ts
Normal file
10
app/lib/cache.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { BentoCache, bentostore } from 'bentocache';
|
||||||
|
import { memoryDriver } from 'bentocache/drivers/memory';
|
||||||
|
|
||||||
|
export const cache = new BentoCache({
|
||||||
|
default: 'cache',
|
||||||
|
|
||||||
|
stores: {
|
||||||
|
cache: bentostore().useL1Layer(memoryDriver({ maxSize: 10_000 })),
|
||||||
|
},
|
||||||
|
});
|
||||||
11
app/middleware/admin_middleware.ts
Normal file
11
app/middleware/admin_middleware.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import type { NextFn } from '@adonisjs/core/types/http';
|
||||||
|
|
||||||
|
export default class AdminMiddleware {
|
||||||
|
async handle(ctx: HttpContext, next: NextFn) {
|
||||||
|
if (!ctx.auth.user?.isAdmin) {
|
||||||
|
return ctx.response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
28
app/middleware/auth_middleware.ts
Normal file
28
app/middleware/auth_middleware.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { Authenticators } from '@adonisjs/auth/types';
|
||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import type { NextFn } from '@adonisjs/core/types/http';
|
||||||
|
import { route } from '@izzyjs/route/client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auth middleware is used authenticate HTTP requests and deny
|
||||||
|
* access to unauthenticated users.
|
||||||
|
*/
|
||||||
|
export default class AuthMiddleware {
|
||||||
|
/**
|
||||||
|
* The URL to redirect to, when authentication fails
|
||||||
|
*/
|
||||||
|
redirectTo = route('auth.login').url;
|
||||||
|
|
||||||
|
async handle(
|
||||||
|
ctx: HttpContext,
|
||||||
|
next: NextFn,
|
||||||
|
options: {
|
||||||
|
guards?: (keyof Authenticators)[];
|
||||||
|
} = {}
|
||||||
|
) {
|
||||||
|
await ctx.auth.authenticateUsing(options.guards, {
|
||||||
|
loginRoute: this.redirectTo,
|
||||||
|
});
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
19
app/middleware/container_bindings_middleware.ts
Normal file
19
app/middleware/container_bindings_middleware.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Logger } from '@adonisjs/core/logger';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import { NextFn } from '@adonisjs/core/types/http';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The container bindings middleware binds classes to their request
|
||||||
|
* specific value using the container resolver.
|
||||||
|
*
|
||||||
|
* - We bind "HttpContext" class to the "ctx" object
|
||||||
|
* - And bind "Logger" class to the "ctx.logger" object
|
||||||
|
*/
|
||||||
|
export default class ContainerBindingsMiddleware {
|
||||||
|
handle(ctx: HttpContext, next: NextFn) {
|
||||||
|
ctx.containerResolver.bindValue(HttpContext, ctx);
|
||||||
|
ctx.containerResolver.bindValue(Logger, ctx.logger);
|
||||||
|
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
31
app/middleware/guest_middleware.ts
Normal file
31
app/middleware/guest_middleware.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import type { NextFn } from '@adonisjs/core/types/http';
|
||||||
|
import type { Authenticators } from '@adonisjs/auth/types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guest middleware is used to deny access to routes that should
|
||||||
|
* be accessed by unauthenticated users.
|
||||||
|
*
|
||||||
|
* For example, the login page should not be accessible if the user
|
||||||
|
* is already logged-in
|
||||||
|
*/
|
||||||
|
export default class GuestMiddleware {
|
||||||
|
/**
|
||||||
|
* The URL to redirect to when user is logged-in
|
||||||
|
*/
|
||||||
|
redirectTo = '/';
|
||||||
|
|
||||||
|
async handle(
|
||||||
|
ctx: HttpContext,
|
||||||
|
next: NextFn,
|
||||||
|
options: { guards?: (keyof Authenticators)[] } = {}
|
||||||
|
) {
|
||||||
|
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
|
||||||
|
if (await ctx.auth.use(guard).check()) {
|
||||||
|
return ctx.response.redirect(this.redirectTo, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
17
app/middleware/log_request.ts
Normal file
17
app/middleware/log_request.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
|
||||||
|
export default class LogRequest {
|
||||||
|
async handle({ request }: HttpContext, next: () => Promise<void>) {
|
||||||
|
if (
|
||||||
|
!request.url().startsWith('/node_modules') &&
|
||||||
|
!request.url().startsWith('/inertia') &&
|
||||||
|
!request.url().startsWith('/@vite') &&
|
||||||
|
!request.url().startsWith('/@react-refresh') &&
|
||||||
|
!request.url().includes('.ts')
|
||||||
|
) {
|
||||||
|
logger.debug(`[${request.method()}]: ${request.url()}`);
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
}
|
||||||
|
}
|
||||||
25
app/models/app_base_model.ts
Normal file
25
app/models/app_base_model.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import {
|
||||||
|
BaseModel,
|
||||||
|
CamelCaseNamingStrategy,
|
||||||
|
column,
|
||||||
|
} from '@adonisjs/lucid/orm';
|
||||||
|
import { DateTime } from 'luxon';
|
||||||
|
|
||||||
|
export default class AppBaseModel extends BaseModel {
|
||||||
|
static namingStrategy = new CamelCaseNamingStrategy();
|
||||||
|
serializeExtras = true;
|
||||||
|
|
||||||
|
@column({ isPrimary: true })
|
||||||
|
declare id: number;
|
||||||
|
|
||||||
|
@column.dateTime({
|
||||||
|
autoCreate: true,
|
||||||
|
})
|
||||||
|
declare createdAt: DateTime;
|
||||||
|
|
||||||
|
@column.dateTime({
|
||||||
|
autoCreate: true,
|
||||||
|
autoUpdate: true,
|
||||||
|
})
|
||||||
|
declare updatedAt: DateTime;
|
||||||
|
}
|
||||||
29
app/models/collection.ts
Normal file
29
app/models/collection.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import AppBaseModel from '#models/app_base_model';
|
||||||
|
import Link from '#models/link';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { belongsTo, column, hasMany } from '@adonisjs/lucid/orm';
|
||||||
|
import type { BelongsTo, HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
|
import { Visibility } from '#enums/visibility';
|
||||||
|
|
||||||
|
export default class Collection extends AppBaseModel {
|
||||||
|
@column()
|
||||||
|
declare name: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare description: string | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare visibility: Visibility;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare nextId: number;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare authorId: number;
|
||||||
|
|
||||||
|
@belongsTo(() => User, { foreignKey: 'authorId' })
|
||||||
|
declare author: BelongsTo<typeof User>;
|
||||||
|
|
||||||
|
@hasMany(() => Link)
|
||||||
|
declare links: HasMany<typeof Link>;
|
||||||
|
}
|
||||||
31
app/models/link.ts
Normal file
31
app/models/link.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import AppBaseModel from '#models/app_base_model';
|
||||||
|
import Collection from '#models/collection';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { belongsTo, column } from '@adonisjs/lucid/orm';
|
||||||
|
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
|
||||||
|
|
||||||
|
export default class Link extends AppBaseModel {
|
||||||
|
@column()
|
||||||
|
declare name: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare description: string | null;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare url: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare favorite: boolean;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare collectionId: number;
|
||||||
|
|
||||||
|
@belongsTo(() => Collection, { foreignKey: 'collectionId' })
|
||||||
|
declare collection: BelongsTo<typeof Collection>;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare authorId: number;
|
||||||
|
|
||||||
|
@belongsTo(() => User, { foreignKey: 'authorId' })
|
||||||
|
declare author: BelongsTo<typeof User>;
|
||||||
|
}
|
||||||
47
app/models/user.ts
Normal file
47
app/models/user.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import Collection from '#models/collection';
|
||||||
|
import Link from '#models/link';
|
||||||
|
import type { GoogleToken } from '@adonisjs/ally/types';
|
||||||
|
import { column, computed, hasMany } from '@adonisjs/lucid/orm';
|
||||||
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
|
import AppBaseModel from './app_base_model.js';
|
||||||
|
|
||||||
|
export default class User extends AppBaseModel {
|
||||||
|
@column()
|
||||||
|
declare email: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare name: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare nickName: string; // public username
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare avatarUrl: string;
|
||||||
|
|
||||||
|
@column()
|
||||||
|
declare isAdmin: boolean;
|
||||||
|
|
||||||
|
@column({ serializeAs: null })
|
||||||
|
declare token?: GoogleToken;
|
||||||
|
|
||||||
|
@column({ serializeAs: null })
|
||||||
|
declare providerId: number;
|
||||||
|
|
||||||
|
@column({ serializeAs: null })
|
||||||
|
declare providerType: 'google';
|
||||||
|
|
||||||
|
@hasMany(() => Collection, {
|
||||||
|
foreignKey: 'authorId',
|
||||||
|
})
|
||||||
|
declare collections: HasMany<typeof Collection>;
|
||||||
|
|
||||||
|
@hasMany(() => Link, {
|
||||||
|
foreignKey: 'authorId',
|
||||||
|
})
|
||||||
|
declare links: HasMany<typeof Link>;
|
||||||
|
|
||||||
|
@computed()
|
||||||
|
get fullname() {
|
||||||
|
return this.nickName || this.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
37
app/validators/collection.ts
Normal file
37
app/validators/collection.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { Visibility } from '#enums/visibility';
|
||||||
|
import vine, { SimpleMessagesProvider } from '@vinejs/vine';
|
||||||
|
|
||||||
|
const params = vine.object({
|
||||||
|
id: vine.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createCollectionValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(254),
|
||||||
|
description: vine.string().trim().maxLength(254).nullable(),
|
||||||
|
visibility: vine.enum(Visibility),
|
||||||
|
nextId: vine.number().optional(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export const updateCollectionValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(254),
|
||||||
|
description: vine.string().trim().maxLength(254).nullable(),
|
||||||
|
visibility: vine.enum(Visibility),
|
||||||
|
nextId: vine.number().optional(),
|
||||||
|
|
||||||
|
params,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export const deleteCollectionValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
params,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
createCollectionValidator.messagesProvider = new SimpleMessagesProvider({
|
||||||
|
name: 'Collection name is required',
|
||||||
|
'visibility.required': 'Collection visibiliy is required',
|
||||||
|
});
|
||||||
43
app/validators/link.ts
Normal file
43
app/validators/link.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
const params = vine.object({
|
||||||
|
id: vine.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createLinkValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(254),
|
||||||
|
description: vine.string().trim().maxLength(300).optional(),
|
||||||
|
url: vine.string().trim(),
|
||||||
|
favorite: vine.boolean(),
|
||||||
|
collectionId: vine.number(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export const updateLinkValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(254),
|
||||||
|
description: vine.string().trim().maxLength(300).optional(),
|
||||||
|
url: vine.string().trim(),
|
||||||
|
favorite: vine.boolean(),
|
||||||
|
collectionId: vine.number(),
|
||||||
|
|
||||||
|
params,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export const deleteLinkValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
params,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export const updateLinkFavoriteStatusValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
favorite: vine.boolean(),
|
||||||
|
|
||||||
|
params: vine.object({
|
||||||
|
id: vine.number(),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
);
|
||||||
11
app/validators/shared_collection.ts
Normal file
11
app/validators/shared_collection.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
const params = vine.object({
|
||||||
|
id: vine.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getSharedCollectionValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
params,
|
||||||
|
})
|
||||||
|
);
|
||||||
7
app/validators/user.ts
Normal file
7
app/validators/user.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const updateUserThemeValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
preferDarkTheme: vine.boolean(),
|
||||||
|
})
|
||||||
|
);
|
||||||
47
bin/console.ts
Normal file
47
bin/console.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Ace entry point
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The "console.ts" file is the entrypoint for booting the AdonisJS
|
||||||
|
| command-line framework and executing commands.
|
||||||
|
|
|
||||||
|
| Commands do not boot the application, unless the currently running command
|
||||||
|
| has "options.startApp" flag set to true.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { Ignitor, prettyPrintError } from '@adonisjs/core';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL to the application root. AdonisJS need it to resolve
|
||||||
|
* paths to file and directories for scaffolding commands
|
||||||
|
*/
|
||||||
|
const APP_ROOT = new URL('../', import.meta.url);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The importer is used to import files in context of the
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
const IMPORTER = (filePath: string) => {
|
||||||
|
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||||
|
return import(new URL(filePath, APP_ROOT).href);
|
||||||
|
}
|
||||||
|
return import(filePath);
|
||||||
|
};
|
||||||
|
|
||||||
|
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||||
|
.tap((app) => {
|
||||||
|
app.booting(async () => {
|
||||||
|
await import('#start/env');
|
||||||
|
});
|
||||||
|
app.listen('SIGTERM', () => app.terminate());
|
||||||
|
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
|
||||||
|
})
|
||||||
|
.ace()
|
||||||
|
.handle(process.argv.splice(2))
|
||||||
|
.catch((error) => {
|
||||||
|
process.exitCode = 1;
|
||||||
|
prettyPrintError(error);
|
||||||
|
});
|
||||||
45
bin/server.ts
Normal file
45
bin/server.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| HTTP server entrypoint
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The "server.ts" file is the entrypoint for starting the AdonisJS HTTP
|
||||||
|
| server. Either you can run this file directly or use the "serve"
|
||||||
|
| command to run this file and monitor file changes
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { Ignitor, prettyPrintError } from '@adonisjs/core';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL to the application root. AdonisJS need it to resolve
|
||||||
|
* paths to file and directories for scaffolding commands
|
||||||
|
*/
|
||||||
|
const APP_ROOT = new URL('../', import.meta.url);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The importer is used to import files in context of the
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
const IMPORTER = (filePath: string) => {
|
||||||
|
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||||
|
return import(new URL(filePath, APP_ROOT).href);
|
||||||
|
}
|
||||||
|
return import(filePath);
|
||||||
|
};
|
||||||
|
|
||||||
|
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||||
|
.tap((app) => {
|
||||||
|
app.booting(async () => {
|
||||||
|
await import('#start/env');
|
||||||
|
});
|
||||||
|
app.listen('SIGTERM', () => app.terminate());
|
||||||
|
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
|
||||||
|
})
|
||||||
|
.httpServer()
|
||||||
|
.start()
|
||||||
|
.catch((error) => {
|
||||||
|
process.exitCode = 1;
|
||||||
|
prettyPrintError(error);
|
||||||
|
});
|
||||||
62
bin/test.ts
Normal file
62
bin/test.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Test runner entrypoint
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The "test.ts" file is the entrypoint for running tests using Japa.
|
||||||
|
|
|
||||||
|
| Either you can run this file directly or use the "test"
|
||||||
|
| command to run this file and monitor file changes.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
process.env.NODE_ENV = 'test';
|
||||||
|
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { Ignitor, prettyPrintError } from '@adonisjs/core';
|
||||||
|
import { configure, processCLIArgs, run } from '@japa/runner';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL to the application root. AdonisJS need it to resolve
|
||||||
|
* paths to file and directories for scaffolding commands
|
||||||
|
*/
|
||||||
|
const APP_ROOT = new URL('../', import.meta.url);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The importer is used to import files in context of the
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
const IMPORTER = (filePath: string) => {
|
||||||
|
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||||
|
return import(new URL(filePath, APP_ROOT).href);
|
||||||
|
}
|
||||||
|
return import(filePath);
|
||||||
|
};
|
||||||
|
|
||||||
|
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||||
|
.tap((app) => {
|
||||||
|
app.booting(async () => {
|
||||||
|
await import('#start/env');
|
||||||
|
});
|
||||||
|
app.listen('SIGTERM', () => app.terminate());
|
||||||
|
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
|
||||||
|
})
|
||||||
|
.testRunner()
|
||||||
|
.configure(async (app) => {
|
||||||
|
const { runnerHooks, ...config } = await import('../tests/bootstrap.js');
|
||||||
|
|
||||||
|
processCLIArgs(process.argv.splice(2));
|
||||||
|
configure({
|
||||||
|
...app.rcFile.tests,
|
||||||
|
...config,
|
||||||
|
...{
|
||||||
|
setup: runnerHooks.setup,
|
||||||
|
teardown: runnerHooks.teardown.concat([() => app.terminate()]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.run(() => run())
|
||||||
|
.catch((error) => {
|
||||||
|
process.exitCode = 1;
|
||||||
|
prettyPrintError(error);
|
||||||
|
});
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
const config = {
|
|
||||||
url: process.env.NEXT_PUBLIC_SITE_URL,
|
|
||||||
name: 'MyLinks',
|
|
||||||
description:
|
|
||||||
'MyLinks is a free and open source software, that lets you manage your bookmarks in an intuitive interface',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
19
config/ally.ts
Normal file
19
config/ally.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import env from '#start/env';
|
||||||
|
import { defineConfig, services } from '@adonisjs/ally';
|
||||||
|
|
||||||
|
const allyConfig = defineConfig({
|
||||||
|
google: services.google({
|
||||||
|
clientId: env.get('GOOGLE_CLIENT_ID'),
|
||||||
|
clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
|
||||||
|
callbackUrl: env.get('GOOGLE_CLIENT_CALLBACK_URL'),
|
||||||
|
prompt: 'select_account',
|
||||||
|
display: 'page',
|
||||||
|
scopes: ['userinfo.email', 'userinfo.profile'],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default allyConfig;
|
||||||
|
|
||||||
|
declare module '@adonisjs/ally/types' {
|
||||||
|
interface SocialProviders extends InferSocialProviders<typeof allyConfig> {}
|
||||||
|
}
|
||||||
40
config/app.ts
Normal file
40
config/app.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import env from '#start/env';
|
||||||
|
import app from '@adonisjs/core/services/app';
|
||||||
|
import { Secret } from '@adonisjs/core/helpers';
|
||||||
|
import { defineConfig } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The app key is used for encrypting cookies, generating signed URLs,
|
||||||
|
* and by the "encryption" module.
|
||||||
|
*
|
||||||
|
* The encryption module will fail to decrypt data if the key is lost or
|
||||||
|
* changed. Therefore it is recommended to keep the app key secure.
|
||||||
|
*/
|
||||||
|
export const appKey = new Secret(env.get('APP_KEY'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The configuration settings used by the HTTP server
|
||||||
|
*/
|
||||||
|
export const http = defineConfig({
|
||||||
|
generateRequestId: true,
|
||||||
|
allowMethodSpoofing: false,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enabling async local storage will let you access HTTP context
|
||||||
|
* from anywhere inside your application.
|
||||||
|
*/
|
||||||
|
useAsyncLocalStorage: false,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manage cookies configuration. The settings for the session id cookie are
|
||||||
|
* defined inside the "config/session.ts" file.
|
||||||
|
*/
|
||||||
|
cookie: {
|
||||||
|
domain: '',
|
||||||
|
path: '/',
|
||||||
|
maxAge: '2h',
|
||||||
|
httpOnly: true,
|
||||||
|
secure: app.inProduction,
|
||||||
|
sameSite: 'lax',
|
||||||
|
},
|
||||||
|
});
|
||||||
28
config/auth.ts
Normal file
28
config/auth.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/auth';
|
||||||
|
import { InferAuthEvents, Authenticators } from '@adonisjs/auth/types';
|
||||||
|
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
|
||||||
|
|
||||||
|
const authConfig = defineConfig({
|
||||||
|
default: 'web',
|
||||||
|
guards: {
|
||||||
|
web: sessionGuard({
|
||||||
|
useRememberMeTokens: false,
|
||||||
|
provider: sessionUserProvider({
|
||||||
|
model: () => import('#models/user'),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default authConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inferring types from the configured auth
|
||||||
|
* guards.
|
||||||
|
*/
|
||||||
|
declare module '@adonisjs/auth/types' {
|
||||||
|
interface Authenticators extends InferAuthenticators<typeof authConfig> {}
|
||||||
|
}
|
||||||
|
declare module '@adonisjs/core/types' {
|
||||||
|
interface EventsList extends InferAuthEvents<Authenticators> {}
|
||||||
|
}
|
||||||
55
config/bodyparser.ts
Normal file
55
config/bodyparser.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/core/bodyparser';
|
||||||
|
|
||||||
|
const bodyParserConfig = defineConfig({
|
||||||
|
/**
|
||||||
|
* The bodyparser middleware will parse the request body
|
||||||
|
* for the following HTTP methods.
|
||||||
|
*/
|
||||||
|
allowedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Config for the "application/x-www-form-urlencoded"
|
||||||
|
* content-type parser
|
||||||
|
*/
|
||||||
|
form: {
|
||||||
|
convertEmptyStringsToNull: true,
|
||||||
|
types: ['application/x-www-form-urlencoded'],
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Config for the JSON parser
|
||||||
|
*/
|
||||||
|
json: {
|
||||||
|
convertEmptyStringsToNull: true,
|
||||||
|
types: [
|
||||||
|
'application/json',
|
||||||
|
'application/json-patch+json',
|
||||||
|
'application/vnd.api+json',
|
||||||
|
'application/csp-report',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Config for the "multipart/form-data" content-type parser.
|
||||||
|
* File uploads are handled by the multipart parser.
|
||||||
|
*/
|
||||||
|
multipart: {
|
||||||
|
/**
|
||||||
|
* Enabling auto process allows bodyparser middleware to
|
||||||
|
* move all uploaded files inside the tmp folder of your
|
||||||
|
* operating system
|
||||||
|
*/
|
||||||
|
autoProcess: true,
|
||||||
|
convertEmptyStringsToNull: true,
|
||||||
|
processManually: [],
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum limit of data to parse including all files
|
||||||
|
* and fields
|
||||||
|
*/
|
||||||
|
limit: '20mb',
|
||||||
|
types: ['multipart/form-data'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default bodyParserConfig;
|
||||||
19
config/cors.ts
Normal file
19
config/cors.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/cors';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration options to tweak the CORS policy. The following
|
||||||
|
* options are documented on the official documentation website.
|
||||||
|
*
|
||||||
|
* https://docs.adonisjs.com/guides/security/cors
|
||||||
|
*/
|
||||||
|
const corsConfig = defineConfig({
|
||||||
|
enabled: true,
|
||||||
|
origin: [],
|
||||||
|
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
|
||||||
|
headers: true,
|
||||||
|
exposeHeaders: [],
|
||||||
|
credentials: true,
|
||||||
|
maxAge: 90,
|
||||||
|
});
|
||||||
|
|
||||||
|
export default corsConfig;
|
||||||
27
config/database.ts
Normal file
27
config/database.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import env from '#start/env';
|
||||||
|
import { defineConfig } from '@adonisjs/lucid';
|
||||||
|
|
||||||
|
const dbConfig = defineConfig({
|
||||||
|
connection: 'postgres',
|
||||||
|
connections: {
|
||||||
|
postgres: {
|
||||||
|
client: 'pg',
|
||||||
|
connection: {
|
||||||
|
host: env.get('DB_HOST'),
|
||||||
|
port: env.get('DB_PORT'),
|
||||||
|
user: env.get('DB_USER'),
|
||||||
|
password: env.get('DB_PASSWORD'),
|
||||||
|
database: env.get('DB_DATABASE'),
|
||||||
|
},
|
||||||
|
migrations: {
|
||||||
|
naturalSort: true,
|
||||||
|
paths: ['database/migrations'],
|
||||||
|
},
|
||||||
|
seeders: {
|
||||||
|
paths: ['./database/seeders/main'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default dbConfig;
|
||||||
24
config/hash.ts
Normal file
24
config/hash.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { defineConfig, drivers } from '@adonisjs/core/hash';
|
||||||
|
|
||||||
|
const hashConfig = defineConfig({
|
||||||
|
default: 'scrypt',
|
||||||
|
|
||||||
|
list: {
|
||||||
|
scrypt: drivers.scrypt({
|
||||||
|
cost: 16384,
|
||||||
|
blockSize: 8,
|
||||||
|
parallelization: 1,
|
||||||
|
maxMemory: 33554432,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default hashConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inferring types for the list of hashers you have configured
|
||||||
|
* in your application.
|
||||||
|
*/
|
||||||
|
declare module '@adonisjs/core/types' {
|
||||||
|
export interface HashersList extends InferHashers<typeof hashConfig> {}
|
||||||
|
}
|
||||||
36
config/inertia.ts
Normal file
36
config/inertia.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import {
|
||||||
|
DARK_THEME_DEFAULT_VALUE,
|
||||||
|
PREFER_DARK_THEME,
|
||||||
|
} from '#constants/session';
|
||||||
|
import { defineConfig } from '@adonisjs/inertia';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
/**
|
||||||
|
* Path to the Edge view that will be used as the root view for Inertia responses
|
||||||
|
*/
|
||||||
|
rootView: 'inertia_layout',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Data that should be shared with all rendered pages
|
||||||
|
*/
|
||||||
|
sharedData: {
|
||||||
|
errors: (ctx) => ctx.session?.flashMessages.get('errors'),
|
||||||
|
preferDarkTheme: (ctx) =>
|
||||||
|
ctx.session?.get(PREFER_DARK_THEME, DARK_THEME_DEFAULT_VALUE),
|
||||||
|
auth: async (ctx) => {
|
||||||
|
await ctx.auth?.check();
|
||||||
|
return {
|
||||||
|
user: ctx.auth?.user || null,
|
||||||
|
isAuthenticated: ctx.auth?.isAuthenticated || false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options for the server-side rendering
|
||||||
|
*/
|
||||||
|
ssr: {
|
||||||
|
enabled: true,
|
||||||
|
entrypoint: 'inertia/app/ssr.tsx',
|
||||||
|
},
|
||||||
|
});
|
||||||
35
config/logger.ts
Normal file
35
config/logger.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import env from '#start/env';
|
||||||
|
import app from '@adonisjs/core/services/app';
|
||||||
|
import { defineConfig, targets } from '@adonisjs/core/logger';
|
||||||
|
|
||||||
|
const loggerConfig = defineConfig({
|
||||||
|
default: 'app',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The loggers object can be used to define multiple loggers.
|
||||||
|
* By default, we configure only one logger (named "app").
|
||||||
|
*/
|
||||||
|
loggers: {
|
||||||
|
app: {
|
||||||
|
enabled: true,
|
||||||
|
name: env.get('APP_NAME'),
|
||||||
|
level: env.get('LOG_LEVEL'),
|
||||||
|
transport: {
|
||||||
|
targets: targets()
|
||||||
|
.pushIf(!app.inProduction, targets.pretty())
|
||||||
|
.pushIf(app.inProduction, targets.file({ destination: 1 }))
|
||||||
|
.toArray(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default loggerConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inferring types for the list of loggers you have configured
|
||||||
|
* in your application.
|
||||||
|
*/
|
||||||
|
declare module '@adonisjs/core/types' {
|
||||||
|
export interface LoggersList extends InferLoggers<typeof loggerConfig> {}
|
||||||
|
}
|
||||||
49
config/session.ts
Normal file
49
config/session.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import env from '#start/env';
|
||||||
|
import { defineConfig, stores } from '@adonisjs/session';
|
||||||
|
|
||||||
|
const sessionConfig = defineConfig({
|
||||||
|
enabled: true,
|
||||||
|
cookieName: 'adonis-session',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When set to true, the session id cookie will be deleted
|
||||||
|
* once the user closes the browser.
|
||||||
|
*/
|
||||||
|
clearWithBrowser: false,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define how long to keep the session data alive without
|
||||||
|
* any activity.
|
||||||
|
*/
|
||||||
|
age: '7d',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration for session cookie and the
|
||||||
|
* cookie store
|
||||||
|
*/
|
||||||
|
cookie: {
|
||||||
|
path: '/',
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
|
||||||
|
// TODO: set this to lax and found a solution to keep auth when using extension
|
||||||
|
sameSite: 'none',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The store to use. Make sure to validate the environment
|
||||||
|
* variable in order to infer the store name without any
|
||||||
|
* errors.
|
||||||
|
*/
|
||||||
|
store: env.get('SESSION_DRIVER'),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List of configured stores. Refer documentation to see
|
||||||
|
* list of available stores and their config.
|
||||||
|
*/
|
||||||
|
stores: {
|
||||||
|
cookie: stores.cookie(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default sessionConfig;
|
||||||
50
config/shield.ts
Normal file
50
config/shield.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/shield';
|
||||||
|
|
||||||
|
const shieldConfig = defineConfig({
|
||||||
|
/**
|
||||||
|
* Configure CSP policies for your app. Refer documentation
|
||||||
|
* to learn more
|
||||||
|
*/
|
||||||
|
csp: {
|
||||||
|
enabled: false,
|
||||||
|
directives: {},
|
||||||
|
reportOnly: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure CSRF protection options. Refer documentation
|
||||||
|
* to learn more
|
||||||
|
*/
|
||||||
|
csrf: {
|
||||||
|
enabled: false,
|
||||||
|
exceptRoutes: [],
|
||||||
|
enableXsrfCookie: true,
|
||||||
|
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Control how your website should be embedded inside
|
||||||
|
* iFrames
|
||||||
|
*/
|
||||||
|
xFrame: {
|
||||||
|
enabled: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force browser to always use HTTPS
|
||||||
|
*/
|
||||||
|
hsts: {
|
||||||
|
enabled: true,
|
||||||
|
maxAge: '180 days',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disable browsers from sniffing the content type of a
|
||||||
|
* response and always rely on the "content-type" header.
|
||||||
|
*/
|
||||||
|
contentTypeSniffing: {
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default shieldConfig;
|
||||||
17
config/static.ts
Normal file
17
config/static.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/static';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration options to tweak the static files middleware.
|
||||||
|
* The complete set of options are documented on the
|
||||||
|
* official documentation website.
|
||||||
|
*
|
||||||
|
* https://docs.adonisjs.com/guides/static-assets
|
||||||
|
*/
|
||||||
|
const staticServerConfig = defineConfig({
|
||||||
|
enabled: true,
|
||||||
|
etag: true,
|
||||||
|
lastModified: true,
|
||||||
|
dotFiles: 'ignore',
|
||||||
|
});
|
||||||
|
|
||||||
|
export default staticServerConfig;
|
||||||
28
config/vite.ts
Normal file
28
config/vite.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { defineConfig } from '@adonisjs/vite';
|
||||||
|
|
||||||
|
const viteBackendConfig = defineConfig({
|
||||||
|
/**
|
||||||
|
* The output of vite will be written inside this
|
||||||
|
* directory. The path should be relative from
|
||||||
|
* the application root.
|
||||||
|
*/
|
||||||
|
buildDirectory: 'public/assets',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The path to the manifest file generated by the
|
||||||
|
* "vite build" command.
|
||||||
|
*/
|
||||||
|
manifestFile: 'public/assets/.vite/manifest.json',
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feel free to change the value of the "assetsUrl" to
|
||||||
|
* point to a CDN in production.
|
||||||
|
*/
|
||||||
|
assetsUrl: '/assets',
|
||||||
|
|
||||||
|
scriptAttributes: {
|
||||||
|
defer: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default viteBackendConfig;
|
||||||
8
database/default_table_fields.ts
Normal file
8
database/default_table_fields.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Knex } from 'knex';
|
||||||
|
|
||||||
|
export function defaultTableFields(table: Knex.CreateTableBuilder) {
|
||||||
|
table.increments('id').primary().first().unique().notNullable();
|
||||||
|
|
||||||
|
table.timestamp('created_at').notNullable();
|
||||||
|
table.timestamp('updated_at').nullable();
|
||||||
|
}
|
||||||
26
database/migrations/1714218548323_create_users_table.ts
Normal file
26
database/migrations/1714218548323_create_users_table.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { defaultTableFields } from '#database/default_table_fields';
|
||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class CreateUsersTable extends BaseSchema {
|
||||||
|
static tableName = 'users';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.createTableIfNotExists(CreateUsersTable.tableName, (table) => {
|
||||||
|
table.string('email', 254).notNullable().unique();
|
||||||
|
table.string('name', 254).notNullable();
|
||||||
|
table.string('nick_name', 254).nullable();
|
||||||
|
table.text('avatar_url').notNullable();
|
||||||
|
table.boolean('is_admin').defaultTo(0).notNullable();
|
||||||
|
|
||||||
|
table.json('token').nullable();
|
||||||
|
table.string('provider_id').notNullable();
|
||||||
|
table.enum('provider_type', ['google']).notNullable().defaultTo('google');
|
||||||
|
|
||||||
|
defaultTableFields(table);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.dropTable(CreateUsersTable.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { defaultTableFields } from '#database/default_table_fields';
|
||||||
|
import { Visibility } from '#enums/visibility';
|
||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class CreateCollectionTable extends BaseSchema {
|
||||||
|
static tableName = 'collections';
|
||||||
|
private visibilityEnumName = 'collection_visibility';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
|
||||||
|
this.schema.createTableIfNotExists(
|
||||||
|
CreateCollectionTable.tableName,
|
||||||
|
(table) => {
|
||||||
|
table.string('name', 254).notNullable();
|
||||||
|
table.string('description', 254).nullable();
|
||||||
|
table
|
||||||
|
.enum('visibility', Object.values(Visibility), {
|
||||||
|
useNative: true,
|
||||||
|
enumName: this.visibilityEnumName,
|
||||||
|
existingType: false,
|
||||||
|
})
|
||||||
|
.nullable()
|
||||||
|
.defaultTo(Visibility.PRIVATE);
|
||||||
|
table
|
||||||
|
.integer('next_id')
|
||||||
|
.references('id')
|
||||||
|
.inTable('collections')
|
||||||
|
.defaultTo(null);
|
||||||
|
table
|
||||||
|
.integer('author_id')
|
||||||
|
.references('id')
|
||||||
|
.inTable('users')
|
||||||
|
.onDelete('CASCADE');
|
||||||
|
|
||||||
|
defaultTableFields(table);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
|
||||||
|
this.schema.dropTable(CreateCollectionTable.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
database/migrations/1714254076754_create_links_table.ts
Normal file
31
database/migrations/1714254076754_create_links_table.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { defaultTableFields } from '#database/default_table_fields';
|
||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class CreateLinksTable extends BaseSchema {
|
||||||
|
static tableName = 'links';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.createTableIfNotExists(CreateLinksTable.tableName, (table) => {
|
||||||
|
table.string('name', 254).notNullable();
|
||||||
|
table.string('description', 254).nullable();
|
||||||
|
table.text('url').notNullable();
|
||||||
|
table.boolean('favorite').notNullable().defaultTo(0);
|
||||||
|
table
|
||||||
|
.integer('collection_id')
|
||||||
|
.references('id')
|
||||||
|
.inTable('collections')
|
||||||
|
.onDelete('CASCADE');
|
||||||
|
table
|
||||||
|
.integer('author_id')
|
||||||
|
.references('id')
|
||||||
|
.inTable('users')
|
||||||
|
.onDelete('CASCADE');
|
||||||
|
|
||||||
|
defaultTableFields(table);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.dropTable(CreateLinksTable.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class extends BaseSchema {
|
||||||
|
async up() {
|
||||||
|
this.schema.raw(`
|
||||||
|
CREATE EXTENSION IF NOT EXISTS unaccent;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
`);
|
||||||
|
this.schema.raw(`
|
||||||
|
CREATE INDEX ON links USING gin(to_tsvector('english', name));
|
||||||
|
CREATE INDEX ON collections USING gin(to_tsvector('english', name));
|
||||||
|
CREATE INDEX ON links USING gin(to_tsvector('french', name));
|
||||||
|
CREATE INDEX ON collections USING gin(to_tsvector('french', name));
|
||||||
|
`);
|
||||||
|
this.schema.raw(`
|
||||||
|
CREATE OR REPLACE FUNCTION search_text(search_query TEXT, p_author_id INTEGER)
|
||||||
|
RETURNS TABLE (
|
||||||
|
id INTEGER,
|
||||||
|
type TEXT,
|
||||||
|
name VARCHAR(254),
|
||||||
|
url TEXT,
|
||||||
|
collection_id INTEGER,
|
||||||
|
matched_part TEXT,
|
||||||
|
rank DOUBLE PRECISION
|
||||||
|
)
|
||||||
|
AS $$
|
||||||
|
BEGIN
|
||||||
|
RETURN QUERY
|
||||||
|
SELECT links.id, 'link' AS type, links.name, links.url, collections.id AS collection_id,
|
||||||
|
ts_headline('english', unaccent(links.name), plainto_tsquery('english', unaccent(search_query))) AS matched_part,
|
||||||
|
ts_rank_cd(to_tsvector('english', unaccent(links.name)), plainto_tsquery('english', unaccent(search_query)))::DOUBLE PRECISION AS rank
|
||||||
|
FROM links
|
||||||
|
LEFT JOIN collections ON links.collection_id = collections.id
|
||||||
|
WHERE unaccent(links.name) ILIKE '%' || unaccent(search_query) || '%'
|
||||||
|
AND (p_author_id IS NULL OR links.author_id = p_author_id)
|
||||||
|
UNION ALL
|
||||||
|
SELECT collections.id, 'collection' AS type, collections.name, NULL AS url, NULL AS collection_id,
|
||||||
|
ts_headline('english', unaccent(collections.name), plainto_tsquery('english', unaccent(search_query))) AS matched_part,
|
||||||
|
ts_rank_cd(to_tsvector('english', unaccent(collections.name)), plainto_tsquery('english', unaccent(search_query)))::DOUBLE PRECISION AS rank
|
||||||
|
FROM collections
|
||||||
|
WHERE unaccent(collections.name) ILIKE '%' || unaccent(search_query) || '%'
|
||||||
|
AND (p_author_id IS NULL OR collections.author_id = p_author_id)
|
||||||
|
ORDER BY rank DESC NULLS LAST, matched_part DESC NULLS LAST;
|
||||||
|
END;
|
||||||
|
$$
|
||||||
|
LANGUAGE plpgsql;
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.raw('DROP FUNCTION IF EXISTS search_text');
|
||||||
|
}
|
||||||
|
}
|
||||||
40
database/seeders/collection_seeder.ts
Normal file
40
database/seeders/collection_seeder.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { Visibility } from '#enums/visibility';
|
||||||
|
import Collection from '#models/collection';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { BaseSeeder } from '@adonisjs/lucid/seeders';
|
||||||
|
import { faker } from '@faker-js/faker';
|
||||||
|
|
||||||
|
export default class extends BaseSeeder {
|
||||||
|
static environment = ['development', 'testing'];
|
||||||
|
|
||||||
|
async run() {
|
||||||
|
const users = await getUserIds();
|
||||||
|
|
||||||
|
const collections = faker.helpers.multiple(
|
||||||
|
() => createRandomCollection(users),
|
||||||
|
{
|
||||||
|
count: 50,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
await Collection.createMany(collections);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserIds() {
|
||||||
|
const users = await User.all();
|
||||||
|
return users.map(({ id }) => id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let collectionId = 0;
|
||||||
|
function createRandomCollection(userIds: User['id'][]) {
|
||||||
|
const authorId = faker.helpers.arrayElements(userIds, 1).at(0);
|
||||||
|
collectionId++;
|
||||||
|
return {
|
||||||
|
id: collectionId,
|
||||||
|
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
|
||||||
|
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
|
||||||
|
visibility: Visibility.PRIVATE,
|
||||||
|
nextId: collectionId + 1,
|
||||||
|
authorId,
|
||||||
|
};
|
||||||
|
}
|
||||||
46
database/seeders/link_seeder.ts
Normal file
46
database/seeders/link_seeder.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { getUserIds } from '#database/seeders/collection_seeder';
|
||||||
|
import Collection from '#models/collection';
|
||||||
|
import Link from '#models/link';
|
||||||
|
import User from '#models/user';
|
||||||
|
import { BaseSeeder } from '@adonisjs/lucid/seeders';
|
||||||
|
import { faker } from '@faker-js/faker';
|
||||||
|
|
||||||
|
export default class extends BaseSeeder {
|
||||||
|
static environment = ['development', 'testing'];
|
||||||
|
|
||||||
|
async run() {
|
||||||
|
const users = await getUserIds();
|
||||||
|
|
||||||
|
const links = await Promise.all(
|
||||||
|
faker.helpers.multiple(async () => createRandomLink(users), {
|
||||||
|
count: 500,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
await Link.createMany(links.filter((a) => typeof a !== 'undefined') as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getCollectionIds(authorId: User['id']) {
|
||||||
|
const collection = await Collection.findManyBy('author_id', authorId);
|
||||||
|
return collection.map(({ id }) => id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createRandomLink(userIds: User['id'][]) {
|
||||||
|
const authorId = faker.helpers.arrayElements(userIds, 1).at(0)!;
|
||||||
|
const collections = await getCollectionIds(authorId);
|
||||||
|
|
||||||
|
const collectionId = faker.helpers.arrayElements(collections, 1).at(0);
|
||||||
|
if (!collectionId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: faker.string.uuid(),
|
||||||
|
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
|
||||||
|
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
|
||||||
|
url: faker.internet.url(),
|
||||||
|
favorite: faker.number.int({ min: 0, max: 1 }),
|
||||||
|
authorId,
|
||||||
|
collectionId,
|
||||||
|
};
|
||||||
|
}
|
||||||
33
database/seeders/main/index_seeder.ts
Normal file
33
database/seeders/main/index_seeder.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import app from '@adonisjs/core/services/app';
|
||||||
|
import logger from '@adonisjs/core/services/logger';
|
||||||
|
import { BaseSeeder } from '@adonisjs/lucid/seeders';
|
||||||
|
|
||||||
|
export default class IndexSeeder extends BaseSeeder {
|
||||||
|
private async seed(Seeder: { default: typeof BaseSeeder }) {
|
||||||
|
/**
|
||||||
|
* Do not run when not in a environment specified in Seeder
|
||||||
|
*/
|
||||||
|
if (
|
||||||
|
!Seeder.default.environment ||
|
||||||
|
(!Seeder.default.environment.includes('development') && app.inDev) ||
|
||||||
|
(!Seeder.default.environment.includes('testing') && app.inTest) ||
|
||||||
|
(!Seeder.default.environment.includes('production') && app.inProduction)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Seeder.default(this.client).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
async run() {
|
||||||
|
logger.info('Start user seed');
|
||||||
|
await this.seed(await import('#database/seeders/user_seeder'));
|
||||||
|
logger.info('User seed done');
|
||||||
|
logger.info('Collection user seed');
|
||||||
|
await this.seed(await import('#database/seeders/collection_seeder'));
|
||||||
|
logger.info('Collection seed done');
|
||||||
|
logger.info('Link user seed');
|
||||||
|
await this.seed(await import('#database/seeders/link_seeder'));
|
||||||
|
logger.info('Link seed done');
|
||||||
|
}
|
||||||
|
}
|
||||||
29
database/seeders/user_seeder.ts
Normal file
29
database/seeders/user_seeder.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import User from '#models/user';
|
||||||
|
import { GoogleToken } from '@adonisjs/ally/types';
|
||||||
|
import { BaseSeeder } from '@adonisjs/lucid/seeders';
|
||||||
|
import { faker } from '@faker-js/faker';
|
||||||
|
|
||||||
|
export default class extends BaseSeeder {
|
||||||
|
static environment = ['development', 'testing'];
|
||||||
|
|
||||||
|
async run() {
|
||||||
|
const users = faker.helpers.multiple(createRandomUser, {
|
||||||
|
count: 25,
|
||||||
|
});
|
||||||
|
await User.createMany(users);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRandomUser() {
|
||||||
|
return {
|
||||||
|
id: faker.number.int(),
|
||||||
|
email: faker.internet.email(),
|
||||||
|
name: faker.internet.userName(),
|
||||||
|
nickName: faker.internet.displayName(),
|
||||||
|
avatarUrl: faker.image.avatar(),
|
||||||
|
isAdmin: false,
|
||||||
|
providerId: faker.number.int(),
|
||||||
|
providerType: 'google' as const,
|
||||||
|
token: {} as GoogleToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,27 +1,34 @@
|
|||||||
|
name: dev-stack
|
||||||
services:
|
services:
|
||||||
mysqldb:
|
postgres:
|
||||||
image: mysql:latest
|
container_name: postgres
|
||||||
restart: always
|
image: postgres:16
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
ports:
|
|
||||||
- '3306:3306'
|
|
||||||
healthcheck:
|
|
||||||
test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD
|
|
||||||
start_period: 5s
|
|
||||||
interval: 5s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 55
|
|
||||||
|
|
||||||
phpmyadmin:
|
|
||||||
image: phpmyadmin:5
|
|
||||||
restart: always
|
restart: always
|
||||||
environment:
|
environment:
|
||||||
- PMA_HOST=mysqldb
|
- POSTGRES_DB=${DB_DATABASE}
|
||||||
- PMA_PORT=3306
|
- POSTGRES_USER=${DB_USER}
|
||||||
env_file:
|
- POSTGRES_PASSWORD=${DB_PASSWORD}
|
||||||
- .env
|
healthcheck:
|
||||||
|
test: ['CMD-SHELL', 'pg_isready']
|
||||||
|
volumes:
|
||||||
|
- postgres_volume:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- '8080:80'
|
- '${DB_PORT}:5432'
|
||||||
|
|
||||||
|
pgadmin:
|
||||||
|
container_name: pgadmin
|
||||||
|
image: dpage/pgadmin4:8.6
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
- PGADMIN_DEFAULT_EMAIL=myemail@gmail.com
|
||||||
|
- PGADMIN_DEFAULT_PASSWORD=a12345678
|
||||||
depends_on:
|
depends_on:
|
||||||
- mysqldb
|
- postgres
|
||||||
|
volumes:
|
||||||
|
- ./docker-config/servers_pgadmin.json:/pgadmin4/servers.json
|
||||||
|
ports:
|
||||||
|
- '5050:80'
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_volume:
|
||||||
|
name: postgres_test_dev_stack
|
||||||
|
|||||||
@@ -1,44 +1,56 @@
|
|||||||
networks:
|
name: my-links
|
||||||
mylinks_app:
|
|
||||||
external: true
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
mylinks:
|
postgres:
|
||||||
|
container_name: postgres
|
||||||
|
image: postgres:16
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
- POSTGRES_DB=${DB_DATABASE}
|
||||||
|
- POSTGRES_USER=${DB_USER}
|
||||||
|
- POSTGRES_PASSWORD=${DB_PASSWORD}
|
||||||
|
healthcheck:
|
||||||
|
test: ['CMD-SHELL', 'pg_isready']
|
||||||
|
volumes:
|
||||||
|
- postgres-volume:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- '${DB_PORT}:5432'
|
||||||
|
|
||||||
|
pgadmin:
|
||||||
|
container_name: pgadmin
|
||||||
|
image: dpage/pgadmin4:8.6
|
||||||
|
restart: always
|
||||||
|
healthcheck:
|
||||||
|
test: ['CMD', 'wget', '-O', '-', 'http://localhost:80/misc/ping']
|
||||||
|
interval: 2s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 30
|
||||||
|
environment:
|
||||||
|
- PGADMIN_DEFAULT_EMAIL=myemail@gmail.com
|
||||||
|
- PGADMIN_DEFAULT_PASSWORD=a12345678
|
||||||
|
depends_on:
|
||||||
|
- postgres
|
||||||
|
volumes:
|
||||||
|
- ./docker-config/servers_pgadmin.json:/pgadmin4/servers.json
|
||||||
|
ports:
|
||||||
|
- '5050:80'
|
||||||
|
|
||||||
|
my-links:
|
||||||
|
container_name: my-links
|
||||||
restart: always
|
restart: always
|
||||||
container_name: MyLinks
|
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
ports:
|
|
||||||
- '127.0.0.1:3000:3000'
|
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=mysql://${MYSQL_USER}:${MYSQL_PASSWORD}@mylinks_db:3306/${MYSQL_DATABASE}
|
- DB_HOST=postgres
|
||||||
networks:
|
- HOST=0.0.0.0
|
||||||
- mylinks_app
|
- NODE_ENV=production
|
||||||
healthcheck:
|
|
||||||
test:
|
|
||||||
[
|
|
||||||
'CMD-SHELL',
|
|
||||||
'wget --spider --tries=1 --no-verbose http://0.0.0.0:3000',
|
|
||||||
]
|
|
||||||
depends_on:
|
|
||||||
mylinks_db:
|
|
||||||
condition: service_started
|
|
||||||
|
|
||||||
mylinks_db:
|
|
||||||
container_name: MyLinksDB
|
|
||||||
image: mysql:latest
|
|
||||||
restart: always
|
|
||||||
volumes:
|
|
||||||
- ./docker-config/mysql-dev-init.sql:/docker-entrypoint-initdb.d/init.sql
|
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
healthcheck:
|
depends_on:
|
||||||
test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD
|
postgres:
|
||||||
start_period: 5s
|
condition: service_healthy
|
||||||
interval: 5s
|
ports:
|
||||||
timeout: 5s
|
- ${PORT}:3333
|
||||||
retries: 55
|
|
||||||
networks:
|
volumes:
|
||||||
- mylinks_app
|
postgres-volume:
|
||||||
|
name: postgres-prod-my-links
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
CREATE DATABASE IF NOT EXISTS mylinks;
|
|
||||||
|
|
||||||
GRANT ALL PRIVILEGES ON DATABASE * TO mluser;
|
|
||||||
13
docker-config/servers_pgadmin.json
Normal file
13
docker-config/servers_pgadmin.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"Servers": {
|
||||||
|
"1": {
|
||||||
|
"Name": "project",
|
||||||
|
"Group": "Servers",
|
||||||
|
"Port": 5432,
|
||||||
|
"Username": "postgres",
|
||||||
|
"Host": "postgres",
|
||||||
|
"SSLMode": "prefer",
|
||||||
|
"MaintenanceDB": "my-links"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
4
eslint.config.js
Normal file
4
eslint.config.js
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import { configApp } from '@adonisjs/eslint-config';
|
||||||
|
export default configApp({
|
||||||
|
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
|
||||||
|
});
|
||||||
17
example.env
17
example.env
@@ -1,17 +0,0 @@
|
|||||||
MYSQL_USER="root"
|
|
||||||
MYSQL_PASSWORD="root"
|
|
||||||
MYSQL_ROOT_PASSWORD="root"
|
|
||||||
MYSQL_DATABASE="mylinks"
|
|
||||||
|
|
||||||
# Or if you need external Database
|
|
||||||
# DATABASE_IP="localhost"
|
|
||||||
# DATABASE_PORT="3306"
|
|
||||||
# DATABASE_URL="mysql://${MYSQL_USER}:${MYSQL_PASSWORD}@${DATABASE_IP}:${DATABASE_PORT}/${MYSQL_DATABASE}"
|
|
||||||
|
|
||||||
NEXTAUTH_URL="http://localhost:3000"
|
|
||||||
NEXT_PUBLIC_SITE_URL="http://localhost:3000"
|
|
||||||
|
|
||||||
NEXTAUTH_SECRET=""
|
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID=""
|
|
||||||
GOOGLE_CLIENT_SECRET=""
|
|
||||||
27
inertia/app/app.tsx
Normal file
27
inertia/app/app.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { resolvePageComponent } from '@adonisjs/inertia/helpers';
|
||||||
|
import { createInertiaApp } from '@inertiajs/react';
|
||||||
|
import 'dayjs/locale/en';
|
||||||
|
import 'dayjs/locale/fr';
|
||||||
|
import { hydrateRoot } from 'react-dom/client';
|
||||||
|
import 'react-toggle/style.css';
|
||||||
|
import { primaryColor } from '~/styles/common_colors';
|
||||||
|
import '../i18n/index';
|
||||||
|
|
||||||
|
const appName = import.meta.env.VITE_APP_NAME || 'MyLinks';
|
||||||
|
|
||||||
|
createInertiaApp({
|
||||||
|
progress: { color: primaryColor },
|
||||||
|
|
||||||
|
title: (title) => `${appName}${title && ` - ${title}`}`,
|
||||||
|
|
||||||
|
resolve: (name) => {
|
||||||
|
return resolvePageComponent(
|
||||||
|
`../pages/${name}.tsx`,
|
||||||
|
import.meta.glob('../pages/**/*.tsx')
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
setup({ el, App, props }) {
|
||||||
|
hydrateRoot(el, <App {...props} />);
|
||||||
|
},
|
||||||
|
});
|
||||||
14
inertia/app/ssr.tsx
Normal file
14
inertia/app/ssr.tsx
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { createInertiaApp } from '@inertiajs/react';
|
||||||
|
import ReactDOMServer from 'react-dom/server';
|
||||||
|
|
||||||
|
export default function render(page: any) {
|
||||||
|
return createInertiaApp({
|
||||||
|
page,
|
||||||
|
render: ReactDOMServer.renderToString,
|
||||||
|
resolve: (name) => {
|
||||||
|
const pages = import.meta.glob('../pages/**/*.tsx', { eager: true });
|
||||||
|
return pages[`../pages/${name}.tsx`];
|
||||||
|
},
|
||||||
|
setup: ({ App, props }) => <App {...props} />,
|
||||||
|
});
|
||||||
|
}
|
||||||
64
inertia/components/common/dropdown/dropdown.tsx
Normal file
64
inertia/components/common/dropdown/dropdown.tsx
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
import { HtmlHTMLAttributes, ReactNode, useRef } from 'react';
|
||||||
|
import DropdownContainer from '~/components/common/dropdown/dropdown_container';
|
||||||
|
import DropdownLabel from '~/components/common/dropdown/dropdown_label';
|
||||||
|
import useClickOutside from '~/hooks/use_click_outside';
|
||||||
|
import useToggle from '~/hooks/use_modal';
|
||||||
|
import useShortcut from '~/hooks/use_shortcut';
|
||||||
|
|
||||||
|
const DropdownStyle = styled.div<{ opened: boolean; svgSize?: number }>(
|
||||||
|
({ opened, theme, svgSize = 24 }) => ({
|
||||||
|
cursor: 'pointer',
|
||||||
|
userSelect: 'none',
|
||||||
|
position: 'relative',
|
||||||
|
minWidth: 'fit-content',
|
||||||
|
width: 'fit-content',
|
||||||
|
maxWidth: '250px',
|
||||||
|
backgroundColor: opened ? theme.colors.secondary : theme.colors.background,
|
||||||
|
padding: '4px',
|
||||||
|
borderRadius: theme.border.radius,
|
||||||
|
|
||||||
|
'&:hover': {
|
||||||
|
backgroundColor: theme.colors.secondary,
|
||||||
|
},
|
||||||
|
|
||||||
|
'& svg': {
|
||||||
|
height: `${svgSize}px`,
|
||||||
|
width: `${svgSize}px`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export default function Dropdown({
|
||||||
|
children,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
svgSize,
|
||||||
|
onClick,
|
||||||
|
}: HtmlHTMLAttributes<HTMLDivElement> & {
|
||||||
|
label: ReactNode | string;
|
||||||
|
className?: string;
|
||||||
|
svgSize?: number;
|
||||||
|
}) {
|
||||||
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
const { isShowing, toggle, close } = useToggle();
|
||||||
|
|
||||||
|
useClickOutside(dropdownRef, close);
|
||||||
|
useShortcut('ESCAPE_KEY', close, { disableGlobalCheck: true });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DropdownStyle
|
||||||
|
opened={isShowing}
|
||||||
|
onClick={(event) => {
|
||||||
|
onClick?.(event);
|
||||||
|
toggle();
|
||||||
|
}}
|
||||||
|
ref={dropdownRef}
|
||||||
|
className={className}
|
||||||
|
svgSize={svgSize}
|
||||||
|
>
|
||||||
|
<DropdownLabel>{label}</DropdownLabel>
|
||||||
|
<DropdownContainer show={isShowing}>{children}</DropdownContainer>
|
||||||
|
</DropdownStyle>
|
||||||
|
);
|
||||||
|
}
|
||||||
21
inertia/components/common/dropdown/dropdown_container.tsx
Normal file
21
inertia/components/common/dropdown/dropdown_container.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
import TransitionLayout from '~/components/layouts/_transition_layout';
|
||||||
|
|
||||||
|
const DropdownContainer = styled(TransitionLayout)<{ show: boolean }>(
|
||||||
|
({ show, theme }) => ({
|
||||||
|
zIndex: 99,
|
||||||
|
position: 'absolute',
|
||||||
|
top: 'calc(100% + 0.5em)',
|
||||||
|
right: 0,
|
||||||
|
minWidth: '175px',
|
||||||
|
backgroundColor: show ? theme.colors.secondary : theme.colors.background,
|
||||||
|
border: `2px solid ${theme.colors.secondary}`,
|
||||||
|
borderRadius: theme.border.radius,
|
||||||
|
boxShadow: theme.colors.boxShadow,
|
||||||
|
display: show ? 'flex' : 'none',
|
||||||
|
flexDirection: 'column',
|
||||||
|
overflow: 'hidden',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
export default DropdownContainer;
|
||||||
31
inertia/components/common/dropdown/dropdown_item.tsx
Normal file
31
inertia/components/common/dropdown/dropdown_item.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
import { Link } from '@inertiajs/react';
|
||||||
|
|
||||||
|
const DropdownItemBase = styled('div', {
|
||||||
|
shouldForwardProp: (propName) => propName !== 'danger',
|
||||||
|
})<{ danger?: boolean }>(({ theme, danger }) => ({
|
||||||
|
fontSize: '14px',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
color: danger ? theme.colors.lightRed : theme.colors.primary,
|
||||||
|
padding: '8px 12px',
|
||||||
|
borderRadius: theme.border.radius,
|
||||||
|
|
||||||
|
'&:hover': {
|
||||||
|
backgroundColor: theme.colors.background,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const DropdownItemButton = styled(DropdownItemBase)({
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.75em',
|
||||||
|
alignItems: 'center',
|
||||||
|
});
|
||||||
|
|
||||||
|
const DropdownItemLink = styled(DropdownItemBase.withComponent(Link))({
|
||||||
|
width: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.75em',
|
||||||
|
alignItems: 'center',
|
||||||
|
});
|
||||||
|
|
||||||
|
export { DropdownItemButton, DropdownItemLink };
|
||||||
11
inertia/components/common/dropdown/dropdown_label.tsx
Normal file
11
inertia/components/common/dropdown/dropdown_label.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
const DropdownLabel = styled.div(({ theme }) => ({
|
||||||
|
height: 'auto',
|
||||||
|
width: 'auto',
|
||||||
|
color: theme.colors.font,
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.35em',
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default DropdownLabel;
|
||||||
18
inertia/components/common/external_link.tsx
Normal file
18
inertia/components/common/external_link.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { AnchorHTMLAttributes, CSSProperties, ReactNode } from 'react';
|
||||||
|
|
||||||
|
export default function ExternalLink({
|
||||||
|
children,
|
||||||
|
title,
|
||||||
|
...props
|
||||||
|
}: AnchorHTMLAttributes<HTMLAnchorElement> & {
|
||||||
|
children: ReactNode;
|
||||||
|
style?: CSSProperties;
|
||||||
|
title?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<a target="_blank" rel="noreferrer" title={title} {...props}>
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
inertia/components/common/form/_button.tsx
Normal file
31
inertia/components/common/form/_button.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
const Button = styled.button<{ danger?: boolean }>(({ theme, danger }) => {
|
||||||
|
const btnColor = !danger ? theme.colors.primary : theme.colors.lightRed;
|
||||||
|
const btnDarkColor = !danger ? theme.colors.darkBlue : theme.colors.lightRed;
|
||||||
|
return {
|
||||||
|
cursor: 'pointer',
|
||||||
|
width: '100%',
|
||||||
|
textTransform: 'uppercase',
|
||||||
|
fontSize: '14px',
|
||||||
|
color: theme.colors.white,
|
||||||
|
background: btnColor,
|
||||||
|
padding: '0.75em',
|
||||||
|
border: `1px solid ${btnColor}`,
|
||||||
|
borderRadius: theme.border.radius,
|
||||||
|
transition: theme.transition.delay,
|
||||||
|
|
||||||
|
'&:disabled': {
|
||||||
|
cursor: 'not-allowed',
|
||||||
|
opacity: '0.5',
|
||||||
|
},
|
||||||
|
|
||||||
|
'&:not(:disabled):hover': {
|
||||||
|
boxShadow: `${btnDarkColor} 0 0 3px 1px`,
|
||||||
|
background: btnDarkColor,
|
||||||
|
color: theme.colors.white,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Button;
|
||||||
10
inertia/components/common/form/_form.tsx
Normal file
10
inertia/components/common/form/_form.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
const Form = styled.form({
|
||||||
|
width: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
gap: '1em',
|
||||||
|
flexDirection: 'column',
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Form;
|
||||||
25
inertia/components/common/form/_form_field.tsx
Normal file
25
inertia/components/common/form/_form_field.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
const FormField = styled('div', {
|
||||||
|
shouldForwardProp: (propName) => propName !== 'required',
|
||||||
|
})<{ required?: boolean }>(({ required, theme }) => ({
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.25em',
|
||||||
|
flexDirection: 'column',
|
||||||
|
|
||||||
|
'& label': {
|
||||||
|
position: 'relative',
|
||||||
|
userSelect: 'none',
|
||||||
|
width: 'fit-content',
|
||||||
|
},
|
||||||
|
|
||||||
|
'& label::after': {
|
||||||
|
position: 'absolute',
|
||||||
|
top: 0,
|
||||||
|
right: '-0.75em',
|
||||||
|
color: theme.colors.lightRed,
|
||||||
|
content: (required ? '"*"' : '""') as any,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default FormField;
|
||||||
9
inertia/components/common/form/_form_field_error.tsx
Normal file
9
inertia/components/common/form/_form_field_error.tsx
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
// TODO: create a global style variable (fontSize)
|
||||||
|
const FormFieldError = styled.p(({ theme }) => ({
|
||||||
|
fontSize: '12px',
|
||||||
|
color: theme.colors.lightRed,
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default FormFieldError;
|
||||||
27
inertia/components/common/form/_input.tsx
Normal file
27
inertia/components/common/form/_input.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import styled from '@emotion/styled';
|
||||||
|
|
||||||
|
const Input = styled.input(({ theme }) => ({
|
||||||
|
width: '100%',
|
||||||
|
color: theme.colors.font,
|
||||||
|
backgroundColor: theme.colors.secondary,
|
||||||
|
padding: '0.75em',
|
||||||
|
border: `1px solid ${theme.colors.lightGrey}`,
|
||||||
|
borderBottom: `2px solid ${theme.colors.lightGrey}`,
|
||||||
|
borderRadius: theme.border.radius,
|
||||||
|
transition: theme.transition.delay,
|
||||||
|
|
||||||
|
'&:focus': {
|
||||||
|
borderBottom: `2px solid ${theme.colors.primary}`,
|
||||||
|
},
|
||||||
|
|
||||||
|
'&:disabled': {
|
||||||
|
opacity: 0.85,
|
||||||
|
},
|
||||||
|
|
||||||
|
'&::placeholder': {
|
||||||
|
fontStyle: 'italic',
|
||||||
|
color: theme.colors.grey,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default Input;
|
||||||
55
inertia/components/common/form/checkbox.tsx
Normal file
55
inertia/components/common/form/checkbox.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { ChangeEvent, Fragment, InputHTMLAttributes, useState } from 'react';
|
||||||
|
import Toggle from 'react-toggle';
|
||||||
|
import FormField from '~/components/common/form/_form_field';
|
||||||
|
import FormFieldError from '~/components/common/form/_form_field_error';
|
||||||
|
|
||||||
|
interface InputProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
|
||||||
|
label: string;
|
||||||
|
name: string;
|
||||||
|
checked: boolean;
|
||||||
|
errors?: string[];
|
||||||
|
onChange?: (name: string, checked: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Checkbox({
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
checked = false,
|
||||||
|
errors = [],
|
||||||
|
onChange,
|
||||||
|
required = false,
|
||||||
|
...props
|
||||||
|
}: InputProps): JSX.Element {
|
||||||
|
const [checkboxChecked, setCheckboxChecked] = useState<boolean>(checked);
|
||||||
|
|
||||||
|
if (typeof window === 'undefined') return <Fragment />;
|
||||||
|
|
||||||
|
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
|
||||||
|
setCheckboxChecked(target.checked);
|
||||||
|
if (onChange) {
|
||||||
|
onChange(target.name, target.checked);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormField
|
||||||
|
css={{ alignItems: 'center', gap: '1em', flexDirection: 'row' }}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
<label htmlFor={name} title={label}>
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
<Toggle
|
||||||
|
{...props}
|
||||||
|
onChange={_onChange}
|
||||||
|
checked={checkboxChecked}
|
||||||
|
placeholder={props.placeholder ?? 'Type something...'}
|
||||||
|
name={name}
|
||||||
|
id={name}
|
||||||
|
/>
|
||||||
|
{errors.length > 0 &&
|
||||||
|
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
|
||||||
|
</FormField>
|
||||||
|
);
|
||||||
|
}
|
||||||
79
inertia/components/common/form/selector.tsx
Normal file
79
inertia/components/common/form/selector.tsx
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { useTheme } from '@emotion/react';
|
||||||
|
import { InputHTMLAttributes, ReactNode, useEffect, useState } from 'react';
|
||||||
|
import Select, {
|
||||||
|
FormatOptionLabelMeta,
|
||||||
|
GroupBase,
|
||||||
|
OptionsOrGroups,
|
||||||
|
} from 'react-select';
|
||||||
|
import FormField from '~/components/common/form/_form_field';
|
||||||
|
|
||||||
|
type Option = { label: string | number; value: string | number };
|
||||||
|
|
||||||
|
interface SelectorProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
|
||||||
|
label: string;
|
||||||
|
name: string;
|
||||||
|
errors?: string[];
|
||||||
|
options: OptionsOrGroups<Option, GroupBase<Option>>;
|
||||||
|
value: number | string;
|
||||||
|
onChangeCallback?: (value: number | string) => void;
|
||||||
|
formatOptionLabel?: (
|
||||||
|
data: Option,
|
||||||
|
formatOptionLabelMeta: FormatOptionLabelMeta<Option>
|
||||||
|
) => ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Selector({
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
errors = [],
|
||||||
|
options,
|
||||||
|
onChangeCallback,
|
||||||
|
formatOptionLabel,
|
||||||
|
required = false,
|
||||||
|
...props
|
||||||
|
}: SelectorProps): JSX.Element {
|
||||||
|
const theme = useTheme();
|
||||||
|
const [selectorValue, setSelectorValue] = useState<Option>();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (options.length === 0) return;
|
||||||
|
|
||||||
|
const option = options.find((o: any) => o.value === value);
|
||||||
|
if (option) {
|
||||||
|
setSelectorValue(option as Option);
|
||||||
|
}
|
||||||
|
}, [options, value]);
|
||||||
|
|
||||||
|
const handleChange = (selectedOption: Option) => {
|
||||||
|
setSelectorValue(selectedOption);
|
||||||
|
if (onChangeCallback) {
|
||||||
|
onChangeCallback(selectedOption.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormField required={required}>
|
||||||
|
{label && (
|
||||||
|
<label htmlFor={name} title={`${name} field`}>
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<Select
|
||||||
|
value={selectorValue}
|
||||||
|
onChange={(newValue) => handleChange(newValue as Option)}
|
||||||
|
options={options}
|
||||||
|
isDisabled={props.disabled}
|
||||||
|
menuPlacement="auto"
|
||||||
|
formatOptionLabel={
|
||||||
|
formatOptionLabel
|
||||||
|
? (val, formatOptionLabelMeta) =>
|
||||||
|
formatOptionLabel(val, formatOptionLabelMeta)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
css={{ color: theme.colors.black }}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
);
|
||||||
|
}
|
||||||
49
inertia/components/common/form/textbox.tsx
Normal file
49
inertia/components/common/form/textbox.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { ChangeEvent, InputHTMLAttributes, useState } from 'react';
|
||||||
|
import FormField from '~/components/common/form/_form_field';
|
||||||
|
import FormFieldError from '~/components/common/form/_form_field_error';
|
||||||
|
import Input from '~/components/common/form/_input';
|
||||||
|
|
||||||
|
interface InputProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
|
||||||
|
label: string;
|
||||||
|
name: string;
|
||||||
|
value?: string;
|
||||||
|
errors?: string[];
|
||||||
|
onChange?: (name: string, value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TextBox({
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
value = '',
|
||||||
|
errors = [],
|
||||||
|
onChange,
|
||||||
|
required = false,
|
||||||
|
...props
|
||||||
|
}: InputProps): JSX.Element {
|
||||||
|
const [inputValue, setInputValue] = useState<string>(value);
|
||||||
|
|
||||||
|
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
|
||||||
|
setInputValue(target.value);
|
||||||
|
if (onChange) {
|
||||||
|
onChange(target.name, target.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormField required={required}>
|
||||||
|
<label htmlFor={name} title={label}>
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
{...props}
|
||||||
|
name={name}
|
||||||
|
onChange={_onChange}
|
||||||
|
value={inputValue}
|
||||||
|
placeholder={props.placeholder ?? 'Type something...'}
|
||||||
|
/>
|
||||||
|
{errors.length > 0 &&
|
||||||
|
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
|
||||||
|
</FormField>
|
||||||
|
);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user