mirror of
https://github.com/fastapi/full-stack-fastapi-template.git
synced 2026-11-03 20:36:27 +00:00
Compare commits
229 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af086764b3 | |||
| a999734689 | |||
| 8ce3ce5903 | |||
| 9ce8526605 | |||
| 14c09b937d | |||
| bb5732dcbc | |||
| 2b2eefc121 | |||
| 1b5dd13044 | |||
| 36767344aa | |||
| 19049f2a74 | |||
| b905768656 | |||
| 93e83c1ad4 | |||
| 9e0146c64c | |||
| d9a21d3b49 | |||
| ed61369c2b | |||
| 17e4fb9141 | |||
| 269040d670 | |||
| d4ae12cd9a | |||
| 5d21a267fc | |||
| 11e165fa71 | |||
| 684256adbe | |||
| 6606bfcb53 | |||
| 1f686689f1 | |||
| 7bba5a85f0 | |||
| 8efef66c5c | |||
| c8b1b3a9b1 | |||
| b5b2929104 | |||
| b15d482605 | |||
| 1e9e561e5f | |||
| 68b86b157f | |||
| 8f7004821a | |||
| 41999a694f | |||
| 06a2ec8a2b | |||
| aff2146d7e | |||
| c147a95563 | |||
| 7a9920ac7b | |||
| a6fbe9df64 | |||
| 3c38ad1188 | |||
| 000580d0ac | |||
| ddd4b1dbfd | |||
| e65b427ab1 | |||
| cc480df776 | |||
| e15831c930 | |||
| b79c7c8e99 | |||
| c6457cb8e1 | |||
| ded08f6d97 | |||
| e31537c430 | |||
| 5d6a109cf2 | |||
| 53849188fe | |||
| d8219050e1 | |||
| 6e1c888af3 | |||
| 68ef020782 | |||
| 2ed7a0887c | |||
| a38afb4676 | |||
| c38581ce26 | |||
| 8faf5c9fc9 | |||
| 8ba2459b75 | |||
| 763afde09b | |||
| 8b8f0698e3 | |||
| 91c35331e4 | |||
| 3865627301 | |||
| 92a3480a60 | |||
| a578dffcae | |||
| 7a4f98c445 | |||
| 960a38aeb6 | |||
| dabeff7801 | |||
| dda7934ed8 | |||
| db7d06b0f8 | |||
| dbf3899b7c | |||
| e20c35d76d | |||
| d421c90af2 | |||
| df66c1d2ce | |||
| ef76179f9f | |||
| 0b16db4fe0 | |||
| 2f0a682bfe | |||
| 90aa3dc274 | |||
| 649a7dae4c | |||
| e66aa0ea55 | |||
| 1bf057bd19 | |||
| 9ad8f57cfd | |||
| 0eb5e18d85 | |||
| bd8b50308c | |||
| df51c2ee6d | |||
| bf0459468f | |||
| 47548490bb | |||
| 7f7c08e22b | |||
| 44ed5b1783 | |||
| eaa443736d | |||
| 9c8c9c60e4 | |||
| c80191445a | |||
| a1dee4dd5d | |||
| 6b3930fd6b | |||
| ef1f64b8f5 | |||
| 13f4e844d3 | |||
| a7202bf3ea | |||
| 9057631fc0 | |||
| f9a1ac7b1c | |||
| a7f4d7dd61 | |||
| d0654b0896 | |||
| 1197f2bac0 | |||
| 8f6e8c9ee4 | |||
| f0e85714be | |||
| 88a5c6448a | |||
| d86e68f211 | |||
| 91062a1f8d | |||
| a2626b2391 | |||
| d31245d53a | |||
| 72cd3c97f3 | |||
| f11bec6aa6 | |||
| cd462c0a84 | |||
| 84ef657406 | |||
| 8882dc53e8 | |||
| b81cec8ea5 | |||
| d1cc75903e | |||
| 933419e79c | |||
| 897ee1481b | |||
| 472e0f254b | |||
| fb361b1bf6 | |||
| 79a7182816 | |||
| 6509aaa8ff | |||
| 314da98a45 | |||
| 6e0674236b | |||
| 3bd0d98f51 | |||
| 7ca1a3f045 | |||
| 78a8a3b4c4 | |||
| e53dc1702b | |||
| c31a12c0fb | |||
| cc10bf6e31 | |||
| 615170dc34 | |||
| c947cb09e1 | |||
| 88505aa683 | |||
| 71efd68518 | |||
| 9523db2f53 | |||
| 1e9cb5ec28 | |||
| d0fbd0e925 | |||
| b8aef74702 | |||
| ccd85b098b | |||
| 98bd7e6350 | |||
| b92de6eb4f | |||
| e5670212ea | |||
| ad72c4d3fd | |||
| 1105ea4c5c | |||
| 8a008f0bc8 | |||
| 2c6d4a0e57 | |||
| dcebccadba | |||
| e3a023da1e | |||
| e9b2f9f480 | |||
| 1538530349 | |||
| 2314dbd2df | |||
| 3628e039f8 | |||
| 529a475c8d | |||
| 7d7b31823f | |||
| 78b68e1ab9 | |||
| e97f7bfd95 | |||
| 6e6b230dfc | |||
| 601f46f6d6 | |||
| 822dbc52b5 | |||
| 28fa02eeb5 | |||
| 73666b0556 | |||
| b117d30675 | |||
| fa9541fb0d | |||
| ba3826e6ce | |||
| 4239d93ea6 | |||
| aed4db7521 | |||
| 33fe25e332 | |||
| cbd464cce5 | |||
| 6874db48b0 | |||
| 802eeeadc9 | |||
| 84bc7e2ca8 | |||
| c8e57bb760 | |||
| c8b3ccce39 | |||
| 31f604264f | |||
| 2b0701e870 | |||
| 6cd3156672 | |||
| 1e20627934 | |||
| 73f6db9488 | |||
| f03db728e7 | |||
| 4c8837c2a6 | |||
| c05bfc8ddc | |||
| 27a6c58fec | |||
| e7975da967 | |||
| 90252c9804 | |||
| 78777ff011 | |||
| 2e30c948cb | |||
| ac25e154ad | |||
| f442b8df52 | |||
| 4f52d86d97 | |||
| b6f37e4fb7 | |||
| 6b79f8c919 | |||
| 0f2805a82d | |||
| 2c572d3af0 | |||
| 6761293df6 | |||
| 80083299eb | |||
| 7eafadd552 | |||
| 7770b3d1b3 | |||
| 569f64cbeb | |||
| fa6e97e0a2 | |||
| c2220b8e68 | |||
| 94a2037f8a | |||
| d4ee4db2f0 | |||
| 4fbbdf4e94 | |||
| 6e7b8fd1df | |||
| 7856fd811b | |||
| 477c5abf14 | |||
| 43435d50dd | |||
| 75fc26192c | |||
| 6aa2296dea | |||
| fa7d42eddd | |||
| a32cb74edd | |||
| 18ea605849 | |||
| a2a1900105 | |||
| 3fbdf21a05 | |||
| f5764acd56 | |||
| 557b44f0e8 | |||
| 85b7d6bc63 | |||
| a7deb9b39c | |||
| 85c1b06400 | |||
| 4fda65bec3 | |||
| 21232c0f9f | |||
| 10ef99cb68 | |||
| b08aec7d98 | |||
| 2e96f05138 | |||
| bbddf944e2 | |||
| 80e6c81977 | |||
| e13d120fd1 | |||
| afc55bdf91 | |||
| 24662000e7 | |||
| 63e54cb9a5 | |||
| ba042eca1f |
@@ -13,7 +13,6 @@ BACKEND_CORS_ORIGINS="http://localhost,http://localhost:5173,https://localhost,h
|
|||||||
SECRET_KEY=changethis
|
SECRET_KEY=changethis
|
||||||
FIRST_SUPERUSER=admin@example.com
|
FIRST_SUPERUSER=admin@example.com
|
||||||
FIRST_SUPERUSER_PASSWORD=changethis
|
FIRST_SUPERUSER_PASSWORD=changethis
|
||||||
USERS_OPEN_REGISTRATION=False
|
|
||||||
|
|
||||||
# Emails
|
# Emails
|
||||||
SMTP_HOST=
|
SMTP_HOST=
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
labels: [question]
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for your interest in this project! 🚀
|
||||||
|
|
||||||
|
Please follow these instructions, fill every question, and do every step. 🙏
|
||||||
|
|
||||||
|
I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
|
||||||
|
|
||||||
|
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
|
||||||
|
|
||||||
|
All that, on top of all the incredible help provided by a bunch of community members, that give a lot of their time to come here and help others.
|
||||||
|
|
||||||
|
That's a lot of work, but if more users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
|
||||||
|
|
||||||
|
By asking questions in a structured way (following this) it will be much easier to help you.
|
||||||
|
|
||||||
|
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
|
||||||
|
|
||||||
|
As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
|
||||||
|
- type: checkboxes
|
||||||
|
id: checks
|
||||||
|
attributes:
|
||||||
|
label: First Check
|
||||||
|
description: Please confirm and check all the following options.
|
||||||
|
options:
|
||||||
|
- label: I added a very descriptive title here.
|
||||||
|
required: true
|
||||||
|
- label: I used the GitHub search to find a similar question and didn't find it.
|
||||||
|
required: true
|
||||||
|
- label: I searched in the documentation/README.
|
||||||
|
required: true
|
||||||
|
- label: I already searched in Google "How to do X" and didn't find any information.
|
||||||
|
required: true
|
||||||
|
- label: I already read and followed all the tutorial in the docs/README and didn't find an answer.
|
||||||
|
required: true
|
||||||
|
- type: checkboxes
|
||||||
|
id: help
|
||||||
|
attributes:
|
||||||
|
label: Commit to Help
|
||||||
|
description: |
|
||||||
|
After submitting this, I commit to one of:
|
||||||
|
|
||||||
|
* Read open questions until I find 2 where I can help someone and add a comment to help there.
|
||||||
|
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
|
||||||
|
|
||||||
|
options:
|
||||||
|
- label: I commit to help with one of those options 👆
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: example
|
||||||
|
attributes:
|
||||||
|
label: Example Code
|
||||||
|
description: |
|
||||||
|
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
|
||||||
|
|
||||||
|
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
|
||||||
|
|
||||||
|
placeholder: |
|
||||||
|
Write your example code here.
|
||||||
|
render: Text
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: |
|
||||||
|
What is the problem, question, or error?
|
||||||
|
|
||||||
|
Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
|
||||||
|
placeholder: |
|
||||||
|
* Open the browser and call the endpoint `/`.
|
||||||
|
* It returns a JSON with `{"message": "Hello World"}`.
|
||||||
|
* But I expected it to return `{"message": "Hello Morty"}`.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: Operating System
|
||||||
|
description: What operating system are you on?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- Windows
|
||||||
|
- macOS
|
||||||
|
- Other
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: os-details
|
||||||
|
attributes:
|
||||||
|
label: Operating System Details
|
||||||
|
description: You can add more details about your operating system here, in particular if you chose "Other".
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: python-version
|
||||||
|
attributes:
|
||||||
|
label: Python Version
|
||||||
|
description: |
|
||||||
|
What Python version are you using?
|
||||||
|
|
||||||
|
You can find the Python version with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python --version
|
||||||
|
```
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: context
|
||||||
|
attributes:
|
||||||
|
label: Additional Context
|
||||||
|
description: Add any additional context information or screenshots you think are useful.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: Security Contact
|
||||||
|
about: Please report security vulnerabilities to security@tiangolo.com
|
||||||
|
- name: Question or Problem
|
||||||
|
about: Ask a question or ask about a problem in GitHub Discussions.
|
||||||
|
url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions
|
||||||
|
- name: Feature Request
|
||||||
|
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
|
||||||
|
url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: Privileged
|
||||||
|
description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for your interest in this project! 🚀
|
||||||
|
|
||||||
|
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/full-stack-fastapi-template/discussions/categories/questions) instead.
|
||||||
|
- type: checkboxes
|
||||||
|
id: privileged
|
||||||
|
attributes:
|
||||||
|
label: Privileged issue
|
||||||
|
description: Confirm that you are allowed to create an issue here.
|
||||||
|
options:
|
||||||
|
- label: I'm @tiangolo or he asked me directly to create an issue here.
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: content
|
||||||
|
attributes:
|
||||||
|
label: Issue Content
|
||||||
|
description: Add the content of the issue here.
|
||||||
@@ -7,12 +7,15 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
|
# Do not deploy in the main repository, only in user projects
|
||||||
|
if: github.repository_owner != 'fastapi'
|
||||||
runs-on:
|
runs-on:
|
||||||
- self-hosted
|
- self-hosted
|
||||||
- production
|
- production
|
||||||
env:
|
env:
|
||||||
ENVIRONMENT: production
|
ENVIRONMENT: production
|
||||||
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
|
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
|
||||||
|
STACK_NAME: ${{ secrets.STACK_NAME_PRODUCTION }}
|
||||||
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
||||||
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
||||||
@@ -25,5 +28,5 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- run: docker compose -f docker-compose.yml build
|
- run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} build
|
||||||
- run: docker compose -f docker-compose.yml up -d
|
- run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} up -d
|
||||||
|
|||||||
@@ -7,12 +7,15 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
|
# Do not deploy in the main repository, only in user projects
|
||||||
|
if: github.repository_owner != 'fastapi'
|
||||||
runs-on:
|
runs-on:
|
||||||
- self-hosted
|
- self-hosted
|
||||||
- staging
|
- staging
|
||||||
env:
|
env:
|
||||||
ENVIRONMENT: staging
|
ENVIRONMENT: staging
|
||||||
DOMAIN: ${{ secrets.DOMAIN_STAGING }}
|
DOMAIN: ${{ secrets.DOMAIN_STAGING }}
|
||||||
|
STACK_NAME: ${{ secrets.STACK_NAME_STAGING }}
|
||||||
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
|
||||||
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
|
||||||
@@ -25,5 +28,5 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- run: docker compose -f docker-compose.yml build
|
- run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} build
|
||||||
- run: docker compose -f docker-compose.yml up -d
|
- run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} up -d
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ on:
|
|||||||
types:
|
types:
|
||||||
- labeled
|
- labeled
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
issues: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
issue-manager:
|
issue-manager:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
latest-changes:
|
latest-changes:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
pull-requests: read
|
||||||
steps:
|
steps:
|
||||||
- name: Dump GitHub context
|
- name: Dump GitHub context
|
||||||
env:
|
env:
|
||||||
@@ -27,7 +29,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
# To allow latest-changes to commit to the main branch
|
# To allow latest-changes to commit to the main branch
|
||||||
token: ${{ secrets.FULL_STACK_FASTAPI_POSTGRESQL_LATEST_CHANGES }}
|
token: ${{ secrets.LATEST_CHANGES }}
|
||||||
- uses: docker://tiangolo/latest-changes:0.3.0
|
- uses: docker://tiangolo/latest-changes:0.3.0
|
||||||
# - uses: tiangolo/latest-changes@main
|
# - uses: tiangolo/latest-changes@main
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
name: Playwright Tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
debug_enabled:
|
||||||
|
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
|
||||||
|
required: false
|
||||||
|
default: 'false'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
test:
|
||||||
|
timeout-minutes: 60
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: lts/*
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.10'
|
||||||
|
- name: Setup tmate session
|
||||||
|
uses: mxschmitt/action-tmate@v3
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
|
||||||
|
with:
|
||||||
|
limit-access-to-actor: true
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
working-directory: frontend
|
||||||
|
- name: Install Playwright Browsers
|
||||||
|
run: npx playwright install --with-deps
|
||||||
|
working-directory: frontend
|
||||||
|
- run: docker compose build
|
||||||
|
- run: docker compose down -v --remove-orphans
|
||||||
|
- run: docker compose up -d
|
||||||
|
- name: Run Playwright tests
|
||||||
|
run: npx playwright test
|
||||||
|
working-directory: frontend
|
||||||
|
- run: docker compose down -v --remove-orphans
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: playwright-report
|
||||||
|
path: frontend/playwright-report/
|
||||||
|
retention-days: 30
|
||||||
|
|
||||||
|
# https://github.com/marketplace/actions/alls-green#why
|
||||||
|
e2e-alls-green: # This job does nothing and is only used for the branch protection
|
||||||
|
if: always()
|
||||||
|
needs:
|
||||||
|
- test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Decide whether the needed jobs succeeded or failed
|
||||||
|
uses: re-actors/alls-green@release/v1
|
||||||
|
with:
|
||||||
|
jobs: ${{ toJSON(needs) }}
|
||||||
@@ -5,13 +5,13 @@ on:
|
|||||||
workflows: [Test]
|
workflows: [Test]
|
||||||
types: [completed]
|
types: [completed]
|
||||||
|
|
||||||
permissions:
|
|
||||||
statuses: write
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
smokeshow:
|
smokeshow:
|
||||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
statuses: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/setup-python@v5
|
- uses: actions/setup-python@v5
|
||||||
@@ -20,12 +20,14 @@ jobs:
|
|||||||
|
|
||||||
- run: pip install smokeshow
|
- run: pip install smokeshow
|
||||||
|
|
||||||
- uses: dawidd6/action-download-artifact@v3.1.2
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
workflow: test.yml
|
name: coverage-html
|
||||||
commit: ${{ github.event.workflow_run.head_sha }}
|
path: backend/htmlcov
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run-id: ${{ github.event.workflow_run.id }}
|
||||||
|
|
||||||
- run: smokeshow upload coverage-html
|
- run: smokeshow upload backend/htmlcov
|
||||||
env:
|
env:
|
||||||
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
|
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
|
||||||
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
|
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
|
||||||
|
|||||||
@@ -1 +1,6 @@
|
|||||||
.vscode
|
.vscode
|
||||||
|
node_modules/
|
||||||
|
/test-results/
|
||||||
|
/playwright-report/
|
||||||
|
/blob-report/
|
||||||
|
/playwright/.cache/
|
||||||
|
|||||||
+16
-13
@@ -1,23 +1,26 @@
|
|||||||
# See https://pre-commit.com for more information
|
# See https://pre-commit.com for more information
|
||||||
# See https://pre-commit.com/hooks.html for more hooks
|
# See https://pre-commit.com/hooks.html for more hooks
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v4.4.0
|
rev: v4.4.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
- id: check-toml
|
- id: check-toml
|
||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
args:
|
args:
|
||||||
- --unsafe
|
- --unsafe
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
- id: trailing-whitespace
|
exclude: ^frontend/src/client/.*
|
||||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
- id: trailing-whitespace
|
||||||
|
exclude: ^frontend/src/client/.*
|
||||||
|
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||||
rev: v0.2.2
|
rev: v0.2.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
args:
|
args:
|
||||||
- --fix
|
- --fix
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
|
|
||||||
ci:
|
ci:
|
||||||
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
|
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
|
||||||
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
|
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
# Full Stack FastAPI Template
|
# Full Stack FastAPI Template
|
||||||
|
|
||||||
<a href="https://github.com/tiangolo/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/tiangolo/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a>
|
<a href="https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/fastapi/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a>
|
||||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/full-stack-fastapi-template.svg" alt="Coverage"></a>
|
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/full-stack-fastapi-template.svg" alt="Coverage"></a>
|
||||||
|
|
||||||
### Dashboard - Dark Mode
|
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-postgresql)
|
|
||||||
|
|
||||||
## Technology Stack and Features
|
## Technology Stack and Features
|
||||||
|
|
||||||
@@ -17,10 +13,11 @@
|
|||||||
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
|
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
|
||||||
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
|
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
|
||||||
- 🤖 An automatically generated frontend client.
|
- 🤖 An automatically generated frontend client.
|
||||||
|
- 🧪 [Playwright](https://playwright.dev) for End-to-End testing.
|
||||||
- 🦇 Dark mode support.
|
- 🦇 Dark mode support.
|
||||||
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
|
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
|
||||||
- 🔒 Secure password hashing by default.
|
- 🔒 Secure password hashing by default.
|
||||||
- 🔑 JWT token authentication.
|
- 🔑 JWT (JSON Web Token) authentication.
|
||||||
- 📫 Email based password recovery.
|
- 📫 Email based password recovery.
|
||||||
- ✅ Tests with [Pytest](https://pytest.org).
|
- ✅ Tests with [Pytest](https://pytest.org).
|
||||||
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
|
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
|
||||||
@@ -29,36 +26,106 @@
|
|||||||
|
|
||||||
### Dashboard Login
|
### Dashboard Login
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Dashboard - Admin
|
### Dashboard - Admin
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Dashboard - Create User
|
### Dashboard - Create User
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Dashboard - Items
|
### Dashboard - Items
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Dashboard - User Settings
|
### Dashboard - User Settings
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
### Interactive API documentation
|
### Dashboard - Dark Mode
|
||||||
|
|
||||||
[](https://github.com/tiangolo/full-stack-fastapi-template)
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
|
### Interactive API Documentation
|
||||||
|
|
||||||
|
[](https://github.com/fastapi/full-stack-fastapi-template)
|
||||||
|
|
||||||
## How to use it
|
## How To Use It
|
||||||
|
|
||||||
You can **just fork or clone** this repository and use it as is.
|
You can **just fork or clone** this repository and use it as is.
|
||||||
|
|
||||||
✨ It just works. ✨
|
✨ It just works. ✨
|
||||||
|
|
||||||
|
### How to Use a Private Repository
|
||||||
|
|
||||||
|
If you want to have a private repository, GitHub won't allow you to simply fork it as it doesn't allow changing the visibility of forks.
|
||||||
|
|
||||||
|
But you can do the following:
|
||||||
|
|
||||||
|
- Create a new GitHub repo, for example `my-full-stack`.
|
||||||
|
- Clone this repository manually, set the name with the name of the project you want to use, for example `my-full-stack`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@github.com:fastapi/full-stack-fastapi-template.git my-full-stack
|
||||||
|
```
|
||||||
|
|
||||||
|
- Enter into the new directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd my-full-stack
|
||||||
|
```
|
||||||
|
|
||||||
|
- Set the new origin to your new repository, copy it from the GitHub interface, for example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git remote set-url origin git@github.com:octocat/my-full-stack.git
|
||||||
|
```
|
||||||
|
|
||||||
|
- Add this repo as another "remote" to allow you to get updates later:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git remote add upstream git@github.com:fastapi/full-stack-fastapi-template.git
|
||||||
|
```
|
||||||
|
|
||||||
|
- Push the code to your new repository:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git push -u origin master
|
||||||
|
```
|
||||||
|
|
||||||
|
### Update From the Original Template
|
||||||
|
|
||||||
|
After cloning the repository, and after doing changes, you might want to get the latest changes from this original template.
|
||||||
|
|
||||||
|
- Make sure you added the original repository as a remote, you can check it with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git remote -v
|
||||||
|
|
||||||
|
origin git@github.com:octocat/my-full-stack.git (fetch)
|
||||||
|
origin git@github.com:octocat/my-full-stack.git (push)
|
||||||
|
upstream git@github.com:fastapi/full-stack-fastapi-template.git (fetch)
|
||||||
|
upstream git@github.com:fastapi/full-stack-fastapi-template.git (push)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Pull the latest changes without merging:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git pull --no-commit upstream master
|
||||||
|
```
|
||||||
|
|
||||||
|
This will download the latest changes from this template without committing them, that way you can check everything is right before committing.
|
||||||
|
|
||||||
|
- If there are conflicts, solve them in your editor.
|
||||||
|
|
||||||
|
- Once you are done, commit the changes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git merge --continue
|
||||||
|
```
|
||||||
|
|
||||||
### Configure
|
### Configure
|
||||||
|
|
||||||
You can then update configs in the `.env` files to customize your configurations.
|
You can then update configs in the `.env` files to customize your configurations.
|
||||||
@@ -69,7 +136,11 @@ Before deploying it, make sure you change at least the values for:
|
|||||||
- `FIRST_SUPERUSER_PASSWORD`
|
- `FIRST_SUPERUSER_PASSWORD`
|
||||||
- `POSTGRES_PASSWORD`
|
- `POSTGRES_PASSWORD`
|
||||||
|
|
||||||
### Generate secret keys
|
You can (and should) pass these as environment variables from secrets.
|
||||||
|
|
||||||
|
Read the [deployment.md](./deployment.md) docs for more details.
|
||||||
|
|
||||||
|
### Generate Secret Keys
|
||||||
|
|
||||||
Some environment variables in the `.env` file have a default value of `changethis`.
|
Some environment variables in the `.env` file have a default value of `changethis`.
|
||||||
|
|
||||||
@@ -81,7 +152,7 @@ python -c "import secrets; print(secrets.token_urlsafe(32))"
|
|||||||
|
|
||||||
Copy the content and use that as password / secret key. And run that again to generate another secure key.
|
Copy the content and use that as password / secret key. And run that again to generate another secure key.
|
||||||
|
|
||||||
## How to use it - alternative with Copier
|
## How To Use It - Alternative With Copier
|
||||||
|
|
||||||
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
|
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
|
||||||
|
|
||||||
@@ -103,25 +174,25 @@ pipx install copier
|
|||||||
|
|
||||||
**Note**: If you have `pipx`, installing copier is optional, you could run it directly.
|
**Note**: If you have `pipx`, installing copier is optional, you could run it directly.
|
||||||
|
|
||||||
### Generate a Project with Copier
|
### Generate a Project With Copier
|
||||||
|
|
||||||
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`.
|
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`.
|
||||||
|
|
||||||
Go to the directory that will be the parent of your project, and run the command with your project's name:
|
Go to the directory that will be the parent of your project, and run the command with your project's name:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust
|
copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have `pipx` and you didn't install `copier`, you can run it directly:
|
If you have `pipx` and you didn't install `copier`, you can run it directly:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pipx run copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust
|
pipx run copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
|
||||||
```
|
```
|
||||||
|
|
||||||
**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/tiangolo/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files.
|
**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/fastapi/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files.
|
||||||
|
|
||||||
### Input variables
|
### Input Variables
|
||||||
|
|
||||||
Copier will ask you for some data, you might want to have at hand before generating the project.
|
Copier will ask you for some data, you might want to have at hand before generating the project.
|
||||||
|
|
||||||
@@ -130,7 +201,7 @@ But don't worry, you can just update any of that in the `.env` files afterwards.
|
|||||||
The input variables, with their default values (some auto generated) are:
|
The input variables, with their default values (some auto generated) are:
|
||||||
|
|
||||||
- `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
|
- `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
|
||||||
- `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels (no spaces) (in .env).
|
- `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels and project name (no spaces, no periods) (in .env).
|
||||||
- `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
|
- `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
|
||||||
- `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
|
- `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
|
||||||
- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
|
- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
|
||||||
|
|||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
Security is very important for this project and its community. 🔒
|
||||||
|
|
||||||
|
Learn more about it below. 👇
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
The latest version or release is supported.
|
||||||
|
|
||||||
|
You are encouraged to write tests for your application and update your versions frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
|
||||||
|
|
||||||
|
I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
|
||||||
|
|
||||||
|
## Public Discussions
|
||||||
|
|
||||||
|
Please restrain from publicly discussing a potential security vulnerability. 🙊
|
||||||
|
|
||||||
|
It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Thanks for your help!
|
||||||
|
|
||||||
|
The community and I thank you for that. 🙇
|
||||||
+1
-1
@@ -183,7 +183,7 @@ $ alembic revision --autogenerate -m "Add column last_name to User model"
|
|||||||
$ alembic upgrade head
|
$ alembic upgrade head
|
||||||
```
|
```
|
||||||
|
|
||||||
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/db/init_db.py` that end in:
|
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/core/db.py` that end in:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
SQLModel.metadata.create_all(engine)
|
SQLModel.metadata.create_all(engine)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ fileConfig(config.config_file_name)
|
|||||||
# target_metadata = None
|
# target_metadata = None
|
||||||
|
|
||||||
from app.models import SQLModel # noqa
|
from app.models import SQLModel # noqa
|
||||||
|
from app.core.config import settings # noqa
|
||||||
|
|
||||||
target_metadata = SQLModel.metadata
|
target_metadata = SQLModel.metadata
|
||||||
|
|
||||||
@@ -29,12 +30,7 @@ target_metadata = SQLModel.metadata
|
|||||||
|
|
||||||
|
|
||||||
def get_url():
|
def get_url():
|
||||||
user = os.getenv("POSTGRES_USER", "postgres")
|
return str(settings.SQLALCHEMY_DATABASE_URI)
|
||||||
password = os.getenv("POSTGRES_PASSWORD", "")
|
|
||||||
server = os.getenv("POSTGRES_SERVER", "db")
|
|
||||||
port = os.getenv("POSTGRES_PORT", "5432")
|
|
||||||
db = os.getenv("POSTGRES_DB", "app")
|
|
||||||
return f"postgresql+psycopg://{user}:{password}@{server}:{port}/{db}"
|
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_offline():
|
def run_migrations_offline():
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Add cascade delete relationships
|
||||||
|
|
||||||
|
Revision ID: 1a31ce608336
|
||||||
|
Revises: d98dd8ec85a3
|
||||||
|
Create Date: 2024-07-31 22:24:34.447891
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
import sqlmodel.sql.sqltypes
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '1a31ce608336'
|
||||||
|
down_revision = 'd98dd8ec85a3'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.alter_column('item', 'owner_id',
|
||||||
|
existing_type=sa.UUID(),
|
||||||
|
nullable=False)
|
||||||
|
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
|
||||||
|
op.create_foreign_key(None, 'item', 'user', ['owner_id'], ['id'], ondelete='CASCADE')
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_constraint(None, 'item', type_='foreignkey')
|
||||||
|
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
|
||||||
|
op.alter_column('item', 'owner_id',
|
||||||
|
existing_type=sa.UUID(),
|
||||||
|
nullable=True)
|
||||||
|
# ### end Alembic commands ###
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
"""Add max length for string(varchar) fields in User and Items models
|
||||||
|
|
||||||
|
Revision ID: 9c0a54914c78
|
||||||
|
Revises: e2412789c190
|
||||||
|
Create Date: 2024-06-17 14:42:44.639457
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
import sqlmodel.sql.sqltypes
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '9c0a54914c78'
|
||||||
|
down_revision = 'e2412789c190'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# Adjust the length of the email field in the User table
|
||||||
|
op.alter_column('user', 'email',
|
||||||
|
existing_type=sa.String(),
|
||||||
|
type_=sa.String(length=255),
|
||||||
|
existing_nullable=False)
|
||||||
|
|
||||||
|
# Adjust the length of the full_name field in the User table
|
||||||
|
op.alter_column('user', 'full_name',
|
||||||
|
existing_type=sa.String(),
|
||||||
|
type_=sa.String(length=255),
|
||||||
|
existing_nullable=True)
|
||||||
|
|
||||||
|
# Adjust the length of the title field in the Item table
|
||||||
|
op.alter_column('item', 'title',
|
||||||
|
existing_type=sa.String(),
|
||||||
|
type_=sa.String(length=255),
|
||||||
|
existing_nullable=False)
|
||||||
|
|
||||||
|
# Adjust the length of the description field in the Item table
|
||||||
|
op.alter_column('item', 'description',
|
||||||
|
existing_type=sa.String(),
|
||||||
|
type_=sa.String(length=255),
|
||||||
|
existing_nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# Revert the length of the email field in the User table
|
||||||
|
op.alter_column('user', 'email',
|
||||||
|
existing_type=sa.String(length=255),
|
||||||
|
type_=sa.String(),
|
||||||
|
existing_nullable=False)
|
||||||
|
|
||||||
|
# Revert the length of the full_name field in the User table
|
||||||
|
op.alter_column('user', 'full_name',
|
||||||
|
existing_type=sa.String(length=255),
|
||||||
|
type_=sa.String(),
|
||||||
|
existing_nullable=True)
|
||||||
|
|
||||||
|
# Revert the length of the title field in the Item table
|
||||||
|
op.alter_column('item', 'title',
|
||||||
|
existing_type=sa.String(length=255),
|
||||||
|
type_=sa.String(),
|
||||||
|
existing_nullable=False)
|
||||||
|
|
||||||
|
# Revert the length of the description field in the Item table
|
||||||
|
op.alter_column('item', 'description',
|
||||||
|
existing_type=sa.String(length=255),
|
||||||
|
type_=sa.String(),
|
||||||
|
existing_nullable=True)
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
"""Edit replace id integers in all models to use UUID instead
|
||||||
|
|
||||||
|
Revision ID: d98dd8ec85a3
|
||||||
|
Revises: 9c0a54914c78
|
||||||
|
Create Date: 2024-07-19 04:08:04.000976
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
import sqlmodel.sql.sqltypes
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd98dd8ec85a3'
|
||||||
|
down_revision = '9c0a54914c78'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# Ensure uuid-ossp extension is available
|
||||||
|
op.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
|
||||||
|
|
||||||
|
# Create a new UUID column with a default UUID value
|
||||||
|
op.add_column('user', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()')))
|
||||||
|
op.add_column('item', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()')))
|
||||||
|
op.add_column('item', sa.Column('new_owner_id', postgresql.UUID(as_uuid=True), nullable=True))
|
||||||
|
|
||||||
|
# Populate the new columns with UUIDs
|
||||||
|
op.execute('UPDATE "user" SET new_id = uuid_generate_v4()')
|
||||||
|
op.execute('UPDATE item SET new_id = uuid_generate_v4()')
|
||||||
|
op.execute('UPDATE item SET new_owner_id = (SELECT new_id FROM "user" WHERE "user".id = item.owner_id)')
|
||||||
|
|
||||||
|
# Set the new_id as not nullable
|
||||||
|
op.alter_column('user', 'new_id', nullable=False)
|
||||||
|
op.alter_column('item', 'new_id', nullable=False)
|
||||||
|
|
||||||
|
# Drop old columns and rename new columns
|
||||||
|
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
|
||||||
|
op.drop_column('item', 'owner_id')
|
||||||
|
op.alter_column('item', 'new_owner_id', new_column_name='owner_id')
|
||||||
|
|
||||||
|
op.drop_column('user', 'id')
|
||||||
|
op.alter_column('user', 'new_id', new_column_name='id')
|
||||||
|
|
||||||
|
op.drop_column('item', 'id')
|
||||||
|
op.alter_column('item', 'new_id', new_column_name='id')
|
||||||
|
|
||||||
|
# Create primary key constraint
|
||||||
|
op.create_primary_key('user_pkey', 'user', ['id'])
|
||||||
|
op.create_primary_key('item_pkey', 'item', ['id'])
|
||||||
|
|
||||||
|
# Recreate foreign key constraint
|
||||||
|
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# Reverse the upgrade process
|
||||||
|
op.add_column('user', sa.Column('old_id', sa.Integer, autoincrement=True))
|
||||||
|
op.add_column('item', sa.Column('old_id', sa.Integer, autoincrement=True))
|
||||||
|
op.add_column('item', sa.Column('old_owner_id', sa.Integer, nullable=True))
|
||||||
|
|
||||||
|
# Populate the old columns with default values
|
||||||
|
# Generate sequences for the integer IDs if not exist
|
||||||
|
op.execute('CREATE SEQUENCE IF NOT EXISTS user_id_seq AS INTEGER OWNED BY "user".old_id')
|
||||||
|
op.execute('CREATE SEQUENCE IF NOT EXISTS item_id_seq AS INTEGER OWNED BY item.old_id')
|
||||||
|
|
||||||
|
op.execute('SELECT setval(\'user_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM "user"), 1), false)')
|
||||||
|
op.execute('SELECT setval(\'item_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM item), 1), false)')
|
||||||
|
|
||||||
|
op.execute('UPDATE "user" SET old_id = nextval(\'user_id_seq\')')
|
||||||
|
op.execute('UPDATE item SET old_id = nextval(\'item_id_seq\'), old_owner_id = (SELECT old_id FROM "user" WHERE "user".id = item.owner_id)')
|
||||||
|
|
||||||
|
# Drop new columns and rename old columns back
|
||||||
|
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
|
||||||
|
op.drop_column('item', 'owner_id')
|
||||||
|
op.alter_column('item', 'old_owner_id', new_column_name='owner_id')
|
||||||
|
|
||||||
|
op.drop_column('user', 'id')
|
||||||
|
op.alter_column('user', 'old_id', new_column_name='id')
|
||||||
|
|
||||||
|
op.drop_column('item', 'id')
|
||||||
|
op.alter_column('item', 'old_id', new_column_name='id')
|
||||||
|
|
||||||
|
# Create primary key constraint
|
||||||
|
op.create_primary_key('user_pkey', 'user', ['id'])
|
||||||
|
op.create_primary_key('item_pkey', 'item', ['id'])
|
||||||
|
|
||||||
|
# Recreate foreign key constraint
|
||||||
|
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
from collections.abc import Generator
|
from collections.abc import Generator
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
|
import jwt
|
||||||
from fastapi import Depends, HTTPException, status
|
from fastapi import Depends, HTTPException, status
|
||||||
from fastapi.security import OAuth2PasswordBearer
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
from jose import JWTError, jwt
|
from jwt.exceptions import InvalidTokenError
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
@@ -32,7 +33,7 @@ def get_current_user(session: SessionDep, token: TokenDep) -> User:
|
|||||||
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
|
||||||
)
|
)
|
||||||
token_data = TokenPayload(**payload)
|
token_data = TokenPayload(**payload)
|
||||||
except (JWTError, ValidationError):
|
except (InvalidTokenError, ValidationError):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
detail="Could not validate credentials",
|
detail="Could not validate credentials",
|
||||||
@@ -51,6 +52,6 @@ CurrentUser = Annotated[User, Depends(get_current_user)]
|
|||||||
def get_current_active_superuser(current_user: CurrentUser) -> User:
|
def get_current_active_superuser(current_user: CurrentUser) -> User:
|
||||||
if not current_user.is_superuser:
|
if not current_user.is_superuser:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400, detail="The user doesn't have enough privileges"
|
status_code=403, detail="The user doesn't have enough privileges"
|
||||||
)
|
)
|
||||||
return current_user
|
return current_user
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
|
import uuid
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
from sqlmodel import func, select
|
from sqlmodel import func, select
|
||||||
|
|
||||||
from app.api.deps import CurrentUser, SessionDep
|
from app.api.deps import CurrentUser, SessionDep
|
||||||
from app.models import Item, ItemCreate, ItemOut, ItemsOut, ItemUpdate, Message
|
from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
@router.get("/", response_model=ItemsOut)
|
@router.get("/", response_model=ItemsPublic)
|
||||||
def read_items(
|
def read_items(
|
||||||
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
|
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
|
||||||
) -> Any:
|
) -> Any:
|
||||||
@@ -18,17 +19,17 @@ def read_items(
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if current_user.is_superuser:
|
if current_user.is_superuser:
|
||||||
statment = select(func.count()).select_from(Item)
|
count_statement = select(func.count()).select_from(Item)
|
||||||
count = session.exec(statment).one()
|
count = session.exec(count_statement).one()
|
||||||
statement = select(Item).offset(skip).limit(limit)
|
statement = select(Item).offset(skip).limit(limit)
|
||||||
items = session.exec(statement).all()
|
items = session.exec(statement).all()
|
||||||
else:
|
else:
|
||||||
statment = (
|
count_statement = (
|
||||||
select(func.count())
|
select(func.count())
|
||||||
.select_from(Item)
|
.select_from(Item)
|
||||||
.where(Item.owner_id == current_user.id)
|
.where(Item.owner_id == current_user.id)
|
||||||
)
|
)
|
||||||
count = session.exec(statment).one()
|
count = session.exec(count_statement).one()
|
||||||
statement = (
|
statement = (
|
||||||
select(Item)
|
select(Item)
|
||||||
.where(Item.owner_id == current_user.id)
|
.where(Item.owner_id == current_user.id)
|
||||||
@@ -37,11 +38,11 @@ def read_items(
|
|||||||
)
|
)
|
||||||
items = session.exec(statement).all()
|
items = session.exec(statement).all()
|
||||||
|
|
||||||
return ItemsOut(data=items, count=count)
|
return ItemsPublic(data=items, count=count)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{id}", response_model=ItemOut)
|
@router.get("/{id}", response_model=ItemPublic)
|
||||||
def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
|
def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
|
||||||
"""
|
"""
|
||||||
Get item by ID.
|
Get item by ID.
|
||||||
"""
|
"""
|
||||||
@@ -53,7 +54,7 @@ def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
|
|||||||
return item
|
return item
|
||||||
|
|
||||||
|
|
||||||
@router.post("/", response_model=ItemOut)
|
@router.post("/", response_model=ItemPublic)
|
||||||
def create_item(
|
def create_item(
|
||||||
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
|
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
|
||||||
) -> Any:
|
) -> Any:
|
||||||
@@ -67,9 +68,13 @@ def create_item(
|
|||||||
return item
|
return item
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{id}", response_model=ItemOut)
|
@router.put("/{id}", response_model=ItemPublic)
|
||||||
def update_item(
|
def update_item(
|
||||||
*, session: SessionDep, current_user: CurrentUser, id: int, item_in: ItemUpdate
|
*,
|
||||||
|
session: SessionDep,
|
||||||
|
current_user: CurrentUser,
|
||||||
|
id: uuid.UUID,
|
||||||
|
item_in: ItemUpdate,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""
|
"""
|
||||||
Update an item.
|
Update an item.
|
||||||
@@ -88,7 +93,9 @@ def update_item(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{id}")
|
@router.delete("/{id}")
|
||||||
def delete_item(session: SessionDep, current_user: CurrentUser, id: int) -> Message:
|
def delete_item(
|
||||||
|
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
|
||||||
|
) -> Message:
|
||||||
"""
|
"""
|
||||||
Delete an item.
|
Delete an item.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
|
|||||||
from app.core import security
|
from app.core import security
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.core.security import get_password_hash
|
from app.core.security import get_password_hash
|
||||||
from app.models import Message, NewPassword, Token, UserOut
|
from app.models import Message, NewPassword, Token, UserPublic
|
||||||
from app.utils import (
|
from app.utils import (
|
||||||
generate_password_reset_token,
|
generate_password_reset_token,
|
||||||
generate_reset_password_email,
|
generate_reset_password_email,
|
||||||
@@ -43,7 +43,7 @@ def login_access_token(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/login/test-token", response_model=UserOut)
|
@router.post("/login/test-token", response_model=UserPublic)
|
||||||
def test_token(current_user: CurrentUser) -> Any:
|
def test_token(current_user: CurrentUser) -> Any:
|
||||||
"""
|
"""
|
||||||
Test access token
|
Test access token
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import uuid
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
@@ -17,9 +18,9 @@ from app.models import (
|
|||||||
UpdatePassword,
|
UpdatePassword,
|
||||||
User,
|
User,
|
||||||
UserCreate,
|
UserCreate,
|
||||||
UserCreateOpen,
|
UserPublic,
|
||||||
UserOut,
|
UserRegister,
|
||||||
UsersOut,
|
UsersPublic,
|
||||||
UserUpdate,
|
UserUpdate,
|
||||||
UserUpdateMe,
|
UserUpdateMe,
|
||||||
)
|
)
|
||||||
@@ -29,24 +30,26 @@ router = APIRouter()
|
|||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersOut
|
"/",
|
||||||
|
dependencies=[Depends(get_current_active_superuser)],
|
||||||
|
response_model=UsersPublic,
|
||||||
)
|
)
|
||||||
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
|
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
|
||||||
"""
|
"""
|
||||||
Retrieve users.
|
Retrieve users.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
statment = select(func.count()).select_from(User)
|
count_statement = select(func.count()).select_from(User)
|
||||||
count = session.exec(statment).one()
|
count = session.exec(count_statement).one()
|
||||||
|
|
||||||
statement = select(User).offset(skip).limit(limit)
|
statement = select(User).offset(skip).limit(limit)
|
||||||
users = session.exec(statement).all()
|
users = session.exec(statement).all()
|
||||||
|
|
||||||
return UsersOut(data=users, count=count)
|
return UsersPublic(data=users, count=count)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserOut
|
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic
|
||||||
)
|
)
|
||||||
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
|
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
|
||||||
"""
|
"""
|
||||||
@@ -72,7 +75,7 @@ def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
|
|||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/me", response_model=UserOut)
|
@router.patch("/me", response_model=UserPublic)
|
||||||
def update_user_me(
|
def update_user_me(
|
||||||
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
|
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
|
||||||
) -> Any:
|
) -> Any:
|
||||||
@@ -114,38 +117,49 @@ def update_password_me(
|
|||||||
return Message(message="Password updated successfully")
|
return Message(message="Password updated successfully")
|
||||||
|
|
||||||
|
|
||||||
@router.get("/me", response_model=UserOut)
|
@router.get("/me", response_model=UserPublic)
|
||||||
def read_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
|
def read_user_me(current_user: CurrentUser) -> Any:
|
||||||
"""
|
"""
|
||||||
Get current user.
|
Get current user.
|
||||||
"""
|
"""
|
||||||
return current_user
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
@router.post("/open", response_model=UserOut)
|
@router.delete("/me", response_model=Message)
|
||||||
def create_user_open(session: SessionDep, user_in: UserCreateOpen) -> Any:
|
def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
|
||||||
|
"""
|
||||||
|
Delete own user.
|
||||||
|
"""
|
||||||
|
if current_user.is_superuser:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403, detail="Super users are not allowed to delete themselves"
|
||||||
|
)
|
||||||
|
statement = delete(Item).where(col(Item.owner_id) == current_user.id)
|
||||||
|
session.exec(statement) # type: ignore
|
||||||
|
session.delete(current_user)
|
||||||
|
session.commit()
|
||||||
|
return Message(message="User deleted successfully")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/signup", response_model=UserPublic)
|
||||||
|
def register_user(session: SessionDep, user_in: UserRegister) -> Any:
|
||||||
"""
|
"""
|
||||||
Create new user without the need to be logged in.
|
Create new user without the need to be logged in.
|
||||||
"""
|
"""
|
||||||
if not settings.USERS_OPEN_REGISTRATION:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Open user registration is forbidden on this server",
|
|
||||||
)
|
|
||||||
user = crud.get_user_by_email(session=session, email=user_in.email)
|
user = crud.get_user_by_email(session=session, email=user_in.email)
|
||||||
if user:
|
if user:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail="The user with this email already exists in the system",
|
detail="The user with this email already exists in the system",
|
||||||
)
|
)
|
||||||
user_create = UserCreate.from_orm(user_in)
|
user_create = UserCreate.model_validate(user_in)
|
||||||
user = crud.create_user(session=session, user_create=user_create)
|
user = crud.create_user(session=session, user_create=user_create)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{user_id}", response_model=UserOut)
|
@router.get("/{user_id}", response_model=UserPublic)
|
||||||
def read_user_by_id(
|
def read_user_by_id(
|
||||||
user_id: int, session: SessionDep, current_user: CurrentUser
|
user_id: uuid.UUID, session: SessionDep, current_user: CurrentUser
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""
|
"""
|
||||||
Get a specific user by id.
|
Get a specific user by id.
|
||||||
@@ -164,12 +178,12 @@ def read_user_by_id(
|
|||||||
@router.patch(
|
@router.patch(
|
||||||
"/{user_id}",
|
"/{user_id}",
|
||||||
dependencies=[Depends(get_current_active_superuser)],
|
dependencies=[Depends(get_current_active_superuser)],
|
||||||
response_model=UserOut,
|
response_model=UserPublic,
|
||||||
)
|
)
|
||||||
def update_user(
|
def update_user(
|
||||||
*,
|
*,
|
||||||
session: SessionDep,
|
session: SessionDep,
|
||||||
user_id: int,
|
user_id: uuid.UUID,
|
||||||
user_in: UserUpdate,
|
user_in: UserUpdate,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""
|
"""
|
||||||
@@ -193,9 +207,9 @@ def update_user(
|
|||||||
return db_user
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/{user_id}")
|
@router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)])
|
||||||
def delete_user(
|
def delete_user(
|
||||||
session: SessionDep, current_user: CurrentUser, user_id: int
|
session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID
|
||||||
) -> Message:
|
) -> Message:
|
||||||
"""
|
"""
|
||||||
Delete a user.
|
Delete a user.
|
||||||
@@ -203,15 +217,10 @@ def delete_user(
|
|||||||
user = session.get(User, user_id)
|
user = session.get(User, user_id)
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(status_code=404, detail="User not found")
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
elif user != current_user and not current_user.is_superuser:
|
if user == current_user:
|
||||||
raise HTTPException(
|
|
||||||
status_code=403, detail="The user doesn't have enough privileges"
|
|
||||||
)
|
|
||||||
elif user == current_user and current_user.is_superuser:
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=403, detail="Super users are not allowed to delete themselves"
|
status_code=403, detail="Super users are not allowed to delete themselves"
|
||||||
)
|
)
|
||||||
|
|
||||||
statement = delete(Item).where(col(Item.owner_id) == user_id)
|
statement = delete(Item).where(col(Item.owner_id) == user_id)
|
||||||
session.exec(statement) # type: ignore
|
session.exec(statement) # type: ignore
|
||||||
session.delete(user)
|
session.delete(user)
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
import logging
|
|
||||||
|
|
||||||
from sqlalchemy import Engine
|
|
||||||
from sqlmodel import Session, select
|
|
||||||
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
|
|
||||||
|
|
||||||
from app.core.db import engine
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
max_tries = 60 * 5 # 5 minutes
|
|
||||||
wait_seconds = 1
|
|
||||||
|
|
||||||
|
|
||||||
@retry(
|
|
||||||
stop=stop_after_attempt(max_tries),
|
|
||||||
wait=wait_fixed(wait_seconds),
|
|
||||||
before=before_log(logger, logging.INFO),
|
|
||||||
after=after_log(logger, logging.WARN),
|
|
||||||
)
|
|
||||||
def init(db_engine: Engine) -> None:
|
|
||||||
try:
|
|
||||||
# Try to create session to check if DB is awake
|
|
||||||
with Session(db_engine) as session:
|
|
||||||
session.exec(select(1))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(e)
|
|
||||||
raise e
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
logger.info("Initializing service")
|
|
||||||
init(engine)
|
|
||||||
logger.info("Service finished initializing")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -34,7 +34,7 @@ class Settings(BaseSettings):
|
|||||||
DOMAIN: str = "localhost"
|
DOMAIN: str = "localhost"
|
||||||
ENVIRONMENT: Literal["local", "staging", "production"] = "local"
|
ENVIRONMENT: Literal["local", "staging", "production"] = "local"
|
||||||
|
|
||||||
@computed_field # type: ignore[misc]
|
@computed_field # type: ignore[prop-decorator]
|
||||||
@property
|
@property
|
||||||
def server_host(self) -> str:
|
def server_host(self) -> str:
|
||||||
# Use HTTPS for anything other than local development
|
# Use HTTPS for anything other than local development
|
||||||
@@ -51,10 +51,10 @@ class Settings(BaseSettings):
|
|||||||
POSTGRES_SERVER: str
|
POSTGRES_SERVER: str
|
||||||
POSTGRES_PORT: int = 5432
|
POSTGRES_PORT: int = 5432
|
||||||
POSTGRES_USER: str
|
POSTGRES_USER: str
|
||||||
POSTGRES_PASSWORD: str
|
POSTGRES_PASSWORD: str = ""
|
||||||
POSTGRES_DB: str = ""
|
POSTGRES_DB: str = ""
|
||||||
|
|
||||||
@computed_field # type: ignore[misc]
|
@computed_field # type: ignore[prop-decorator]
|
||||||
@property
|
@property
|
||||||
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
|
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
|
||||||
return MultiHostUrl.build(
|
return MultiHostUrl.build(
|
||||||
@@ -84,7 +84,7 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
|
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
|
||||||
|
|
||||||
@computed_field # type: ignore[misc]
|
@computed_field # type: ignore[prop-decorator]
|
||||||
@property
|
@property
|
||||||
def emails_enabled(self) -> bool:
|
def emails_enabled(self) -> bool:
|
||||||
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
|
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
|
||||||
@@ -94,7 +94,6 @@ class Settings(BaseSettings):
|
|||||||
# TODO: update type to EmailStr when sqlmodel supports it
|
# TODO: update type to EmailStr when sqlmodel supports it
|
||||||
FIRST_SUPERUSER: str
|
FIRST_SUPERUSER: str
|
||||||
FIRST_SUPERUSER_PASSWORD: str
|
FIRST_SUPERUSER_PASSWORD: str
|
||||||
USERS_OPEN_REGISTRATION: bool = False
|
|
||||||
|
|
||||||
def _check_default_secret(self, var_name: str, value: str | None) -> None:
|
def _check_default_secret(self, var_name: str, value: str | None) -> None:
|
||||||
if value == "changethis":
|
if value == "changethis":
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
|
|||||||
|
|
||||||
# make sure all SQLModel models are imported (app.models) before initializing DB
|
# make sure all SQLModel models are imported (app.models) before initializing DB
|
||||||
# otherwise, SQLModel might fail to initialize relationships properly
|
# otherwise, SQLModel might fail to initialize relationships properly
|
||||||
# for more details: https://github.com/tiangolo/full-stack-fastapi-template/issues/28
|
# for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28
|
||||||
|
|
||||||
|
|
||||||
def init_db(session: Session) -> None:
|
def init_db(session: Session) -> None:
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from jose import jwt
|
import jwt
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
@@ -13,7 +13,7 @@ ALGORITHM = "HS256"
|
|||||||
|
|
||||||
|
|
||||||
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
|
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
|
||||||
expire = datetime.utcnow() + expires_delta
|
expire = datetime.now(timezone.utc) + expires_delta
|
||||||
to_encode = {"exp": expire, "sub": str(subject)}
|
to_encode = {"exp": expire, "sub": str(subject)}
|
||||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
|
||||||
return encoded_jwt
|
return encoded_jwt
|
||||||
|
|||||||
+2
-1
@@ -1,3 +1,4 @@
|
|||||||
|
import uuid
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
@@ -45,7 +46,7 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
|
|||||||
return db_user
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
def create_item(*, session: Session, item_in: ItemCreate, owner_id: int) -> Item:
|
def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid.UUID) -> Item:
|
||||||
db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
|
db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
|
||||||
session.add(db_item)
|
session.add(db_item)
|
||||||
session.commit()
|
session.commit()
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import sentry_sdk
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.routing import APIRoute
|
from fastapi.routing import APIRoute
|
||||||
from starlette.middleware.cors import CORSMiddleware
|
from starlette.middleware.cors import CORSMiddleware
|
||||||
@@ -10,6 +11,9 @@ def custom_generate_unique_id(route: APIRoute) -> str:
|
|||||||
return f"{route.tags[0]}-{route.name}"
|
return f"{route.tags[0]}-{route.name}"
|
||||||
|
|
||||||
|
|
||||||
|
if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
|
||||||
|
sentry_sdk.init(dsn=str(settings.SENTRY_DSN), enable_tracing=True)
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title=settings.PROJECT_NAME,
|
title=settings.PROJECT_NAME,
|
||||||
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
||||||
|
|||||||
+38
-37
@@ -1,94 +1,95 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from pydantic import EmailStr
|
||||||
from sqlmodel import Field, Relationship, SQLModel
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
# Shared properties
|
# Shared properties
|
||||||
# TODO replace email str with EmailStr when sqlmodel supports it
|
|
||||||
class UserBase(SQLModel):
|
class UserBase(SQLModel):
|
||||||
email: str = Field(unique=True, index=True)
|
email: EmailStr = Field(unique=True, index=True, max_length=255)
|
||||||
is_active: bool = True
|
is_active: bool = True
|
||||||
is_superuser: bool = False
|
is_superuser: bool = False
|
||||||
full_name: str | None = None
|
full_name: str | None = Field(default=None, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
# Properties to receive via API on creation
|
# Properties to receive via API on creation
|
||||||
class UserCreate(UserBase):
|
class UserCreate(UserBase):
|
||||||
password: str
|
password: str = Field(min_length=8, max_length=40)
|
||||||
|
|
||||||
|
|
||||||
# TODO replace email str with EmailStr when sqlmodel supports it
|
class UserRegister(SQLModel):
|
||||||
class UserCreateOpen(SQLModel):
|
email: EmailStr = Field(max_length=255)
|
||||||
email: str
|
password: str = Field(min_length=8, max_length=40)
|
||||||
password: str
|
full_name: str | None = Field(default=None, max_length=255)
|
||||||
full_name: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
# Properties to receive via API on update, all are optional
|
# Properties to receive via API on update, all are optional
|
||||||
# TODO replace email str with EmailStr when sqlmodel supports it
|
|
||||||
class UserUpdate(UserBase):
|
class UserUpdate(UserBase):
|
||||||
email: str | None = None # type: ignore
|
email: EmailStr | None = Field(default=None, max_length=255) # type: ignore
|
||||||
password: str | None = None
|
password: str | None = Field(default=None, min_length=8, max_length=40)
|
||||||
|
|
||||||
|
|
||||||
# TODO replace email str with EmailStr when sqlmodel supports it
|
|
||||||
class UserUpdateMe(SQLModel):
|
class UserUpdateMe(SQLModel):
|
||||||
full_name: str | None = None
|
full_name: str | None = Field(default=None, max_length=255)
|
||||||
email: str | None = None
|
email: EmailStr | None = Field(default=None, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
class UpdatePassword(SQLModel):
|
class UpdatePassword(SQLModel):
|
||||||
current_password: str
|
current_password: str = Field(min_length=8, max_length=40)
|
||||||
new_password: str
|
new_password: str = Field(min_length=8, max_length=40)
|
||||||
|
|
||||||
|
|
||||||
# Database model, database table inferred from class name
|
# Database model, database table inferred from class name
|
||||||
class User(UserBase, table=True):
|
class User(UserBase, table=True):
|
||||||
id: int | None = Field(default=None, primary_key=True)
|
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
|
||||||
hashed_password: str
|
hashed_password: str
|
||||||
items: list["Item"] = Relationship(back_populates="owner")
|
items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)
|
||||||
|
|
||||||
|
|
||||||
# Properties to return via API, id is always required
|
# Properties to return via API, id is always required
|
||||||
class UserOut(UserBase):
|
class UserPublic(UserBase):
|
||||||
id: int
|
id: uuid.UUID
|
||||||
|
|
||||||
|
|
||||||
class UsersOut(SQLModel):
|
class UsersPublic(SQLModel):
|
||||||
data: list[UserOut]
|
data: list[UserPublic]
|
||||||
count: int
|
count: int
|
||||||
|
|
||||||
|
|
||||||
# Shared properties
|
# Shared properties
|
||||||
class ItemBase(SQLModel):
|
class ItemBase(SQLModel):
|
||||||
title: str
|
title: str = Field(min_length=1, max_length=255)
|
||||||
description: str | None = None
|
description: str | None = Field(default=None, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
# Properties to receive on item creation
|
# Properties to receive on item creation
|
||||||
class ItemCreate(ItemBase):
|
class ItemCreate(ItemBase):
|
||||||
title: str
|
title: str = Field(min_length=1, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
# Properties to receive on item update
|
# Properties to receive on item update
|
||||||
class ItemUpdate(ItemBase):
|
class ItemUpdate(ItemBase):
|
||||||
title: str | None = None # type: ignore
|
title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore
|
||||||
|
|
||||||
|
|
||||||
# Database model, database table inferred from class name
|
# Database model, database table inferred from class name
|
||||||
class Item(ItemBase, table=True):
|
class Item(ItemBase, table=True):
|
||||||
id: int | None = Field(default=None, primary_key=True)
|
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
|
||||||
title: str
|
title: str = Field(max_length=255)
|
||||||
owner_id: int | None = Field(default=None, foreign_key="user.id", nullable=False)
|
owner_id: uuid.UUID = Field(
|
||||||
|
foreign_key="user.id", nullable=False, ondelete="CASCADE"
|
||||||
|
)
|
||||||
owner: User | None = Relationship(back_populates="items")
|
owner: User | None = Relationship(back_populates="items")
|
||||||
|
|
||||||
|
|
||||||
# Properties to return via API, id is always required
|
# Properties to return via API, id is always required
|
||||||
class ItemOut(ItemBase):
|
class ItemPublic(ItemBase):
|
||||||
id: int
|
id: uuid.UUID
|
||||||
owner_id: int
|
owner_id: uuid.UUID
|
||||||
|
|
||||||
|
|
||||||
class ItemsOut(SQLModel):
|
class ItemsPublic(SQLModel):
|
||||||
data: list[ItemOut]
|
data: list[ItemPublic]
|
||||||
count: int
|
count: int
|
||||||
|
|
||||||
|
|
||||||
@@ -105,9 +106,9 @@ class Token(SQLModel):
|
|||||||
|
|
||||||
# Contents of JWT token
|
# Contents of JWT token
|
||||||
class TokenPayload(SQLModel):
|
class TokenPayload(SQLModel):
|
||||||
sub: int | None = None
|
sub: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class NewPassword(SQLModel):
|
class NewPassword(SQLModel):
|
||||||
token: str
|
token: str
|
||||||
new_password: str
|
new_password: str = Field(min_length=8, max_length=40)
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
@@ -6,7 +8,7 @@ from app.tests.utils.item import create_random_item
|
|||||||
|
|
||||||
|
|
||||||
def test_create_item(
|
def test_create_item(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
data = {"title": "Foo", "description": "Fighters"}
|
data = {"title": "Foo", "description": "Fighters"}
|
||||||
response = client.post(
|
response = client.post(
|
||||||
@@ -34,15 +36,15 @@ def test_read_item(
|
|||||||
content = response.json()
|
content = response.json()
|
||||||
assert content["title"] == item.title
|
assert content["title"] == item.title
|
||||||
assert content["description"] == item.description
|
assert content["description"] == item.description
|
||||||
assert content["id"] == item.id
|
assert content["id"] == str(item.id)
|
||||||
assert content["owner_id"] == item.owner_id
|
assert content["owner_id"] == str(item.owner_id)
|
||||||
|
|
||||||
|
|
||||||
def test_read_item_not_found(
|
def test_read_item_not_found(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
response = client.get(
|
response = client.get(
|
||||||
f"{settings.API_V1_STR}/items/999",
|
f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
|
||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
)
|
)
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
@@ -91,16 +93,16 @@ def test_update_item(
|
|||||||
content = response.json()
|
content = response.json()
|
||||||
assert content["title"] == data["title"]
|
assert content["title"] == data["title"]
|
||||||
assert content["description"] == data["description"]
|
assert content["description"] == data["description"]
|
||||||
assert content["id"] == item.id
|
assert content["id"] == str(item.id)
|
||||||
assert content["owner_id"] == item.owner_id
|
assert content["owner_id"] == str(item.owner_id)
|
||||||
|
|
||||||
|
|
||||||
def test_update_item_not_found(
|
def test_update_item_not_found(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
data = {"title": "Updated title", "description": "Updated description"}
|
data = {"title": "Updated title", "description": "Updated description"}
|
||||||
response = client.put(
|
response = client.put(
|
||||||
f"{settings.API_V1_STR}/items/999",
|
f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
|
||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
@@ -138,10 +140,10 @@ def test_delete_item(
|
|||||||
|
|
||||||
|
|
||||||
def test_delete_item_not_found(
|
def test_delete_item_not_found(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
response = client.delete(
|
response = client.delete(
|
||||||
f"{settings.API_V1_STR}/items/999",
|
f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
|
||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
)
|
)
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from pytest_mock import MockerFixture
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
|
from app.core.security import verify_password
|
||||||
|
from app.models import User
|
||||||
from app.utils import generate_password_reset_token
|
from app.utils import generate_password_reset_token
|
||||||
|
|
||||||
|
|
||||||
@@ -39,18 +43,19 @@ def test_use_access_token(
|
|||||||
|
|
||||||
|
|
||||||
def test_recovery_password(
|
def test_recovery_password(
|
||||||
client: TestClient, normal_user_token_headers: dict[str, str], mocker: MockerFixture
|
client: TestClient, normal_user_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
mocker.patch("app.utils.send_email", return_value=None)
|
with (
|
||||||
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
|
patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
|
||||||
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
|
patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
|
||||||
email = "test@example.com"
|
):
|
||||||
r = client.post(
|
email = "test@example.com"
|
||||||
f"{settings.API_V1_STR}/password-recovery/{email}",
|
r = client.post(
|
||||||
headers=normal_user_token_headers,
|
f"{settings.API_V1_STR}/password-recovery/{email}",
|
||||||
)
|
headers=normal_user_token_headers,
|
||||||
assert r.status_code == 200
|
)
|
||||||
assert r.json() == {"message": "Password recovery email sent"}
|
assert r.status_code == 200
|
||||||
|
assert r.json() == {"message": "Password recovery email sent"}
|
||||||
|
|
||||||
|
|
||||||
def test_recovery_password_user_not_exits(
|
def test_recovery_password_user_not_exits(
|
||||||
@@ -65,7 +70,7 @@ def test_recovery_password_user_not_exits(
|
|||||||
|
|
||||||
|
|
||||||
def test_reset_password(
|
def test_reset_password(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str]
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
) -> None:
|
) -> None:
|
||||||
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER)
|
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER)
|
||||||
data = {"new_password": "changethis", "token": token}
|
data = {"new_password": "changethis", "token": token}
|
||||||
@@ -77,6 +82,11 @@ def test_reset_password(
|
|||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
assert r.json() == {"message": "Password updated successfully"}
|
assert r.json() == {"message": "Password updated successfully"}
|
||||||
|
|
||||||
|
user_query = select(User).where(User.email == settings.FIRST_SUPERUSER)
|
||||||
|
user = db.exec(user_query).first()
|
||||||
|
assert user
|
||||||
|
assert verify_password(data["new_password"], user.hashed_password)
|
||||||
|
|
||||||
|
|
||||||
def test_reset_password_invalid_token(
|
def test_reset_password_invalid_token(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str]
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
|
import uuid
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from pytest_mock import MockerFixture
|
from sqlmodel import Session, select
|
||||||
from sqlmodel import Session
|
|
||||||
|
|
||||||
from app import crud
|
from app import crud
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.models import UserCreate
|
from app.core.security import verify_password
|
||||||
|
from app.models import User, UserCreate
|
||||||
from app.tests.utils.utils import random_email, random_lower_string
|
from app.tests.utils.utils import random_email, random_lower_string
|
||||||
|
|
||||||
|
|
||||||
@@ -31,27 +34,26 @@ def test_get_users_normal_user_me(
|
|||||||
|
|
||||||
|
|
||||||
def test_create_user_new_email(
|
def test_create_user_new_email(
|
||||||
client: TestClient,
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
superuser_token_headers: dict[str, str],
|
|
||||||
db: Session,
|
|
||||||
mocker: MockerFixture,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
mocker.patch("app.utils.send_email")
|
with (
|
||||||
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
|
patch("app.utils.send_email", return_value=None),
|
||||||
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
|
patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
|
||||||
username = random_email()
|
patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
|
||||||
password = random_lower_string()
|
):
|
||||||
data = {"email": username, "password": password}
|
username = random_email()
|
||||||
r = client.post(
|
password = random_lower_string()
|
||||||
f"{settings.API_V1_STR}/users/",
|
data = {"email": username, "password": password}
|
||||||
headers=superuser_token_headers,
|
r = client.post(
|
||||||
json=data,
|
f"{settings.API_V1_STR}/users/",
|
||||||
)
|
headers=superuser_token_headers,
|
||||||
assert 200 <= r.status_code < 300
|
json=data,
|
||||||
created_user = r.json()
|
)
|
||||||
user = crud.get_user_by_email(session=db, email=username)
|
assert 200 <= r.status_code < 300
|
||||||
assert user
|
created_user = r.json()
|
||||||
assert user.email == created_user["email"]
|
user = crud.get_user_by_email(session=db, email=username)
|
||||||
|
assert user
|
||||||
|
assert user.email == created_user["email"]
|
||||||
|
|
||||||
|
|
||||||
def test_get_existing_user(
|
def test_get_existing_user(
|
||||||
@@ -101,10 +103,10 @@ def test_get_existing_user_current_user(client: TestClient, db: Session) -> None
|
|||||||
|
|
||||||
|
|
||||||
def test_get_existing_user_permissions_error(
|
def test_get_existing_user_permissions_error(
|
||||||
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
|
client: TestClient, normal_user_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
r = client.get(
|
r = client.get(
|
||||||
f"{settings.API_V1_STR}/users/999999",
|
f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
|
||||||
headers=normal_user_token_headers,
|
headers=normal_user_token_headers,
|
||||||
)
|
)
|
||||||
assert r.status_code == 403
|
assert r.status_code == 403
|
||||||
@@ -141,7 +143,7 @@ def test_create_user_by_normal_user(
|
|||||||
headers=normal_user_token_headers,
|
headers=normal_user_token_headers,
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
assert r.status_code == 400
|
assert r.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
def test_retrieve_users(
|
def test_retrieve_users(
|
||||||
@@ -182,6 +184,12 @@ def test_update_user_me(
|
|||||||
assert updated_user["email"] == email
|
assert updated_user["email"] == email
|
||||||
assert updated_user["full_name"] == full_name
|
assert updated_user["full_name"] == full_name
|
||||||
|
|
||||||
|
user_query = select(User).where(User.email == email)
|
||||||
|
user_db = db.exec(user_query).first()
|
||||||
|
assert user_db
|
||||||
|
assert user_db.email == email
|
||||||
|
assert user_db.full_name == full_name
|
||||||
|
|
||||||
|
|
||||||
def test_update_password_me(
|
def test_update_password_me(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
@@ -200,6 +208,12 @@ def test_update_password_me(
|
|||||||
updated_user = r.json()
|
updated_user = r.json()
|
||||||
assert updated_user["message"] == "Password updated successfully"
|
assert updated_user["message"] == "Password updated successfully"
|
||||||
|
|
||||||
|
user_query = select(User).where(User.email == settings.FIRST_SUPERUSER)
|
||||||
|
user_db = db.exec(user_query).first()
|
||||||
|
assert user_db
|
||||||
|
assert user_db.email == settings.FIRST_SUPERUSER
|
||||||
|
assert verify_password(new_password, user_db.hashed_password)
|
||||||
|
|
||||||
# Revert to the old password to keep consistency in test
|
# Revert to the old password to keep consistency in test
|
||||||
old_data = {
|
old_data = {
|
||||||
"current_password": new_password,
|
"current_password": new_password,
|
||||||
@@ -210,11 +224,14 @@ def test_update_password_me(
|
|||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
json=old_data,
|
json=old_data,
|
||||||
)
|
)
|
||||||
|
db.refresh(user_db)
|
||||||
|
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
|
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
|
||||||
|
|
||||||
|
|
||||||
def test_update_password_me_incorrect_password(
|
def test_update_password_me_incorrect_password(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
new_password = random_lower_string()
|
new_password = random_lower_string()
|
||||||
data = {"current_password": new_password, "new_password": new_password}
|
data = {"current_password": new_password, "new_password": new_password}
|
||||||
@@ -247,7 +264,7 @@ def test_update_user_me_email_exists(
|
|||||||
|
|
||||||
|
|
||||||
def test_update_password_me_same_password_error(
|
def test_update_password_me_same_password_error(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
data = {
|
data = {
|
||||||
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
|
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
|
||||||
@@ -265,14 +282,13 @@ def test_update_password_me_same_password_error(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
|
def test_register_user(client: TestClient, db: Session) -> None:
|
||||||
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
|
|
||||||
username = random_email()
|
username = random_email()
|
||||||
password = random_lower_string()
|
password = random_lower_string()
|
||||||
full_name = random_lower_string()
|
full_name = random_lower_string()
|
||||||
data = {"email": username, "password": password, "full_name": full_name}
|
data = {"email": username, "password": password, "full_name": full_name}
|
||||||
r = client.post(
|
r = client.post(
|
||||||
f"{settings.API_V1_STR}/users/open",
|
f"{settings.API_V1_STR}/users/signup",
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
@@ -280,27 +296,15 @@ def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
|
|||||||
assert created_user["email"] == username
|
assert created_user["email"] == username
|
||||||
assert created_user["full_name"] == full_name
|
assert created_user["full_name"] == full_name
|
||||||
|
|
||||||
|
user_query = select(User).where(User.email == username)
|
||||||
def test_create_user_open_forbidden_error(
|
user_db = db.exec(user_query).first()
|
||||||
client: TestClient, mocker: MockerFixture
|
assert user_db
|
||||||
) -> None:
|
assert user_db.email == username
|
||||||
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", False)
|
assert user_db.full_name == full_name
|
||||||
username = random_email()
|
assert verify_password(password, user_db.hashed_password)
|
||||||
password = random_lower_string()
|
|
||||||
full_name = random_lower_string()
|
|
||||||
data = {"email": username, "password": password, "full_name": full_name}
|
|
||||||
r = client.post(
|
|
||||||
f"{settings.API_V1_STR}/users/open",
|
|
||||||
json=data,
|
|
||||||
)
|
|
||||||
assert r.status_code == 403
|
|
||||||
assert r.json()["detail"] == "Open user registration is forbidden on this server"
|
|
||||||
|
|
||||||
|
|
||||||
def test_create_user_open_already_exists_error(
|
def test_register_user_already_exists_error(client: TestClient) -> None:
|
||||||
client: TestClient, mocker: MockerFixture
|
|
||||||
) -> None:
|
|
||||||
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
|
|
||||||
password = random_lower_string()
|
password = random_lower_string()
|
||||||
full_name = random_lower_string()
|
full_name = random_lower_string()
|
||||||
data = {
|
data = {
|
||||||
@@ -309,7 +313,7 @@ def test_create_user_open_already_exists_error(
|
|||||||
"full_name": full_name,
|
"full_name": full_name,
|
||||||
}
|
}
|
||||||
r = client.post(
|
r = client.post(
|
||||||
f"{settings.API_V1_STR}/users/open",
|
f"{settings.API_V1_STR}/users/signup",
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
assert r.status_code == 400
|
assert r.status_code == 400
|
||||||
@@ -332,15 +336,22 @@ def test_update_user(
|
|||||||
)
|
)
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
updated_user = r.json()
|
updated_user = r.json()
|
||||||
|
|
||||||
assert updated_user["full_name"] == "Updated_full_name"
|
assert updated_user["full_name"] == "Updated_full_name"
|
||||||
|
|
||||||
|
user_query = select(User).where(User.email == username)
|
||||||
|
user_db = db.exec(user_query).first()
|
||||||
|
db.refresh(user_db)
|
||||||
|
assert user_db
|
||||||
|
assert user_db.full_name == "Updated_full_name"
|
||||||
|
|
||||||
|
|
||||||
def test_update_user_not_exists(
|
def test_update_user_not_exists(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
data = {"full_name": "Updated_full_name"}
|
data = {"full_name": "Updated_full_name"}
|
||||||
r = client.patch(
|
r = client.patch(
|
||||||
f"{settings.API_V1_STR}/users/99999999",
|
f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
|
||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
@@ -371,24 +382,7 @@ def test_update_user_email_exists(
|
|||||||
assert r.json()["detail"] == "User with this email already exists"
|
assert r.json()["detail"] == "User with this email already exists"
|
||||||
|
|
||||||
|
|
||||||
def test_delete_user_super_user(
|
def test_delete_user_me(client: TestClient, db: Session) -> None:
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
|
||||||
) -> None:
|
|
||||||
username = random_email()
|
|
||||||
password = random_lower_string()
|
|
||||||
user_in = UserCreate(email=username, password=password)
|
|
||||||
user = crud.create_user(session=db, user_create=user_in)
|
|
||||||
user_id = user.id
|
|
||||||
r = client.delete(
|
|
||||||
f"{settings.API_V1_STR}/users/{user_id}",
|
|
||||||
headers=superuser_token_headers,
|
|
||||||
)
|
|
||||||
assert r.status_code == 200
|
|
||||||
deleted_user = r.json()
|
|
||||||
assert deleted_user["message"] == "User deleted successfully"
|
|
||||||
|
|
||||||
|
|
||||||
def test_delete_user_current_user(client: TestClient, db: Session) -> None:
|
|
||||||
username = random_email()
|
username = random_email()
|
||||||
password = random_lower_string()
|
password = random_lower_string()
|
||||||
user_in = UserCreate(email=username, password=password)
|
user_in = UserCreate(email=username, password=password)
|
||||||
@@ -405,19 +399,56 @@ def test_delete_user_current_user(client: TestClient, db: Session) -> None:
|
|||||||
headers = {"Authorization": f"Bearer {a_token}"}
|
headers = {"Authorization": f"Bearer {a_token}"}
|
||||||
|
|
||||||
r = client.delete(
|
r = client.delete(
|
||||||
f"{settings.API_V1_STR}/users/{user_id}",
|
f"{settings.API_V1_STR}/users/me",
|
||||||
headers=headers,
|
headers=headers,
|
||||||
)
|
)
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
deleted_user = r.json()
|
deleted_user = r.json()
|
||||||
assert deleted_user["message"] == "User deleted successfully"
|
assert deleted_user["message"] == "User deleted successfully"
|
||||||
|
result = db.exec(select(User).where(User.id == user_id)).first()
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
user_query = select(User).where(User.id == user_id)
|
||||||
|
user_db = db.execute(user_query).first()
|
||||||
|
assert user_db is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_me_as_superuser(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
|
) -> None:
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/me",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
response = r.json()
|
||||||
|
assert response["detail"] == "Super users are not allowed to delete themselves"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_super_user(
|
||||||
|
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
||||||
|
) -> None:
|
||||||
|
username = random_email()
|
||||||
|
password = random_lower_string()
|
||||||
|
user_in = UserCreate(email=username, password=password)
|
||||||
|
user = crud.create_user(session=db, user_create=user_in)
|
||||||
|
user_id = user.id
|
||||||
|
r = client.delete(
|
||||||
|
f"{settings.API_V1_STR}/users/{user_id}",
|
||||||
|
headers=superuser_token_headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
deleted_user = r.json()
|
||||||
|
assert deleted_user["message"] == "User deleted successfully"
|
||||||
|
result = db.exec(select(User).where(User.id == user_id)).first()
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
def test_delete_user_not_found(
|
def test_delete_user_not_found(
|
||||||
client: TestClient, superuser_token_headers: dict[str, str], db: Session
|
client: TestClient, superuser_token_headers: dict[str, str]
|
||||||
) -> None:
|
) -> None:
|
||||||
r = client.delete(
|
r = client.delete(
|
||||||
f"{settings.API_V1_STR}/users/99999999",
|
f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
|
||||||
headers=superuser_token_headers,
|
headers=superuser_token_headers,
|
||||||
)
|
)
|
||||||
assert r.status_code == 404
|
assert r.status_code == 404
|
||||||
|
|||||||
@@ -1,33 +1,33 @@
|
|||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from pytest_mock import MockerFixture
|
|
||||||
from sqlmodel import select
|
from sqlmodel import select
|
||||||
|
|
||||||
from app.backend_pre_start import init, logger
|
from app.backend_pre_start import init, logger
|
||||||
|
|
||||||
|
|
||||||
def test_init_successful_connection(mocker: MockerFixture) -> None:
|
def test_init_successful_connection() -> None:
|
||||||
engine_mock = MagicMock()
|
engine_mock = MagicMock()
|
||||||
|
|
||||||
session_mock = MagicMock()
|
session_mock = MagicMock()
|
||||||
exec_mock = MagicMock(return_value=True)
|
exec_mock = MagicMock(return_value=True)
|
||||||
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
||||||
mocker.patch("sqlmodel.Session", return_value=session_mock)
|
|
||||||
|
|
||||||
mocker.patch.object(logger, "info")
|
with (
|
||||||
mocker.patch.object(logger, "error")
|
patch("sqlmodel.Session", return_value=session_mock),
|
||||||
mocker.patch.object(logger, "warn")
|
patch.object(logger, "info"),
|
||||||
|
patch.object(logger, "error"),
|
||||||
|
patch.object(logger, "warn"),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
init(engine_mock)
|
||||||
|
connection_successful = True
|
||||||
|
except Exception:
|
||||||
|
connection_successful = False
|
||||||
|
|
||||||
try:
|
assert (
|
||||||
init(engine_mock)
|
connection_successful
|
||||||
connection_successful = True
|
), "The database connection should be successful and not raise an exception."
|
||||||
except Exception:
|
|
||||||
connection_successful = False
|
|
||||||
|
|
||||||
assert (
|
assert session_mock.exec.called_once_with(
|
||||||
connection_successful
|
select(1)
|
||||||
), "The database connection should be successful and not raise an exception."
|
), "The session should execute a select statement once."
|
||||||
|
|
||||||
assert session_mock.exec.called_once_with(
|
|
||||||
select(1)
|
|
||||||
), "The session should execute a select statement once."
|
|
||||||
|
|||||||
@@ -1,33 +1,33 @@
|
|||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from pytest_mock import MockerFixture
|
|
||||||
from sqlmodel import select
|
from sqlmodel import select
|
||||||
|
|
||||||
from app.tests_pre_start import init, logger
|
from app.tests_pre_start import init, logger
|
||||||
|
|
||||||
|
|
||||||
def test_init_successful_connection(mocker: MockerFixture) -> None:
|
def test_init_successful_connection() -> None:
|
||||||
engine_mock = MagicMock()
|
engine_mock = MagicMock()
|
||||||
|
|
||||||
session_mock = MagicMock()
|
session_mock = MagicMock()
|
||||||
exec_mock = MagicMock(return_value=True)
|
exec_mock = MagicMock(return_value=True)
|
||||||
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
session_mock.configure_mock(**{"exec.return_value": exec_mock})
|
||||||
mocker.patch("sqlmodel.Session", return_value=session_mock)
|
|
||||||
|
|
||||||
mocker.patch.object(logger, "info")
|
with (
|
||||||
mocker.patch.object(logger, "error")
|
patch("sqlmodel.Session", return_value=session_mock),
|
||||||
mocker.patch.object(logger, "warn")
|
patch.object(logger, "info"),
|
||||||
|
patch.object(logger, "error"),
|
||||||
|
patch.object(logger, "warn"),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
init(engine_mock)
|
||||||
|
connection_successful = True
|
||||||
|
except Exception:
|
||||||
|
connection_successful = False
|
||||||
|
|
||||||
try:
|
assert (
|
||||||
init(engine_mock)
|
connection_successful
|
||||||
connection_successful = True
|
), "The database connection should be successful and not raise an exception."
|
||||||
except Exception:
|
|
||||||
connection_successful = False
|
|
||||||
|
|
||||||
assert (
|
assert session_mock.exec.called_once_with(
|
||||||
connection_successful
|
select(1)
|
||||||
), "The database connection should be successful and not raise an exception."
|
), "The session should execute a select statement once."
|
||||||
|
|
||||||
assert session_mock.exec.called_once_with(
|
|
||||||
select(1)
|
|
||||||
), "The session should execute a select statement once."
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import logging
|
import logging
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import emails # type: ignore
|
import emails # type: ignore
|
||||||
|
import jwt
|
||||||
from jinja2 import Template
|
from jinja2 import Template
|
||||||
from jose import JWTError, jwt
|
from jwt.exceptions import InvalidTokenError
|
||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
|
|
||||||
@@ -97,7 +98,7 @@ def generate_new_account_email(
|
|||||||
|
|
||||||
def generate_password_reset_token(email: str) -> str:
|
def generate_password_reset_token(email: str) -> str:
|
||||||
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
|
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
|
||||||
now = datetime.utcnow()
|
now = datetime.now(timezone.utc)
|
||||||
expires = now + delta
|
expires = now + delta
|
||||||
exp = expires.timestamp()
|
exp = expires.timestamp()
|
||||||
encoded_jwt = jwt.encode(
|
encoded_jwt = jwt.encode(
|
||||||
@@ -112,5 +113,5 @@ def verify_password_reset_token(token: str) -> str | None:
|
|||||||
try:
|
try:
|
||||||
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
||||||
return str(decoded_token["sub"])
|
return str(decoded_token["sub"])
|
||||||
except JWTError:
|
except InvalidTokenError:
|
||||||
return None
|
return None
|
||||||
|
|||||||
Generated
+661
-834
File diff suppressed because it is too large
Load Diff
+8
-13
@@ -15,43 +15,37 @@ tenacity = "^8.2.3"
|
|||||||
pydantic = ">2.0"
|
pydantic = ">2.0"
|
||||||
emails = "^0.6"
|
emails = "^0.6"
|
||||||
|
|
||||||
gunicorn = "^21.2.0"
|
gunicorn = "^22.0.0"
|
||||||
jinja2 = "^3.1.2"
|
jinja2 = "^3.1.4"
|
||||||
alembic = "^1.12.1"
|
alembic = "^1.12.1"
|
||||||
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
|
|
||||||
httpx = "^0.25.1"
|
httpx = "^0.25.1"
|
||||||
psycopg = {extras = ["binary"], version = "^3.1.13"}
|
psycopg = {extras = ["binary"], version = "^3.1.13"}
|
||||||
sqlmodel = "^0.0.16"
|
sqlmodel = "^0.0.21"
|
||||||
# Pin bcrypt until passlib supports the latest
|
# Pin bcrypt until passlib supports the latest
|
||||||
bcrypt = "4.0.1"
|
bcrypt = "4.0.1"
|
||||||
pydantic-settings = "^2.2.1"
|
pydantic-settings = "^2.2.1"
|
||||||
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
|
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
|
||||||
|
pyjwt = "^2.8.0"
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
pytest = "^7.4.3"
|
pytest = "^7.4.3"
|
||||||
pytest-cov = "^4.1.0"
|
|
||||||
mypy = "^1.8.0"
|
mypy = "^1.8.0"
|
||||||
ruff = "^0.2.2"
|
ruff = "^0.2.2"
|
||||||
pre-commit = "^3.6.2"
|
pre-commit = "^3.6.2"
|
||||||
pytest-mock = "^3.12.0"
|
|
||||||
types-python-jose = "^3.3.4.20240106"
|
|
||||||
types-passlib = "^1.7.7.20240106"
|
types-passlib = "^1.7.7.20240106"
|
||||||
|
coverage = "^7.4.3"
|
||||||
|
|
||||||
[tool.isort]
|
|
||||||
multi_line_output = 3
|
|
||||||
include_trailing_comma = true
|
|
||||||
force_grid_wrap = 0
|
|
||||||
line_length = 88
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["poetry>=0.12"]
|
requires = ["poetry>=0.12"]
|
||||||
build-backend = "poetry.masonry.api"
|
build-backend = "poetry.masonry.api"
|
||||||
|
|
||||||
[tool.mypy]
|
[tool.mypy]
|
||||||
strict = true
|
strict = true
|
||||||
exclude = ["venv", "alembic"]
|
exclude = ["venv", ".venv", "alembic"]
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
target-version = "py310"
|
target-version = "py310"
|
||||||
|
exclude = ["alembic"]
|
||||||
|
|
||||||
[tool.ruff.lint]
|
[tool.ruff.lint]
|
||||||
select = [
|
select = [
|
||||||
@@ -62,6 +56,7 @@ select = [
|
|||||||
"B", # flake8-bugbear
|
"B", # flake8-bugbear
|
||||||
"C4", # flake8-comprehensions
|
"C4", # flake8-comprehensions
|
||||||
"UP", # pyupgrade
|
"UP", # pyupgrade
|
||||||
|
"ARG001", # unused arguments in functions
|
||||||
]
|
]
|
||||||
ignore = [
|
ignore = [
|
||||||
"E501", # line too long, handled by black
|
"E501", # line too long, handled by black
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/bin/sh -e
|
|
||||||
set -x
|
|
||||||
|
|
||||||
# Sort imports one per line, so autoflake can remove unused imports
|
|
||||||
isort --recursive --force-single-line-imports --apply app
|
|
||||||
sh ./scripts/format.sh
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#!/bin/sh -e
|
#!/bin/sh -e
|
||||||
set -x
|
set -x
|
||||||
|
|
||||||
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place app --exclude=__init__.py
|
ruff check app scripts --fix
|
||||||
black app
|
ruff format app scripts
|
||||||
isort --recursive --apply app
|
|
||||||
|
|||||||
@@ -4,5 +4,5 @@ set -e
|
|||||||
set -x
|
set -x
|
||||||
|
|
||||||
mypy app
|
mypy app
|
||||||
ruff app
|
ruff check app
|
||||||
ruff format app --check
|
ruff format app --check
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -e
|
|
||||||
set -x
|
|
||||||
|
|
||||||
bash scripts/test.sh --cov-report=html "${@}"
|
|
||||||
+14
-2
@@ -127,11 +127,12 @@ export DOMAIN=fastapi-project.example.com
|
|||||||
|
|
||||||
You can set several variables, like:
|
You can set several variables, like:
|
||||||
|
|
||||||
|
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
|
||||||
|
* `STACK_NAME`: The name of the stack used for Docker Compose labels and project name, this should be different for `staging`, `production`, etc. You could use the same domain replacing dots with dashes, e.g. `fastapi-project-example-com` and `staging-fastapi-project-example-com`.
|
||||||
* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
|
* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
|
||||||
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
|
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
|
||||||
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
|
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
|
||||||
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
|
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
|
||||||
* `USERS_OPEN_REGISTRATION`: Whether to allow open registration of new users.
|
|
||||||
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
|
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
|
||||||
* `SMTP_USER`: The SMTP server user to send emails.
|
* `SMTP_USER`: The SMTP server user to send emails.
|
||||||
* `SMTP_PASSWORD`: The SMTP server password to send emails.
|
* `SMTP_PASSWORD`: The SMTP server password to send emails.
|
||||||
@@ -143,6 +144,13 @@ You can set several variables, like:
|
|||||||
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
|
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
|
||||||
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
|
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
|
||||||
|
|
||||||
|
## GitHub Actions Environment Variables
|
||||||
|
|
||||||
|
There are some environment variables only used by GitHub Actions that you can configure:
|
||||||
|
|
||||||
|
* `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details.
|
||||||
|
* `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key.
|
||||||
|
|
||||||
### Generate secret keys
|
### Generate secret keys
|
||||||
|
|
||||||
Some environment variables in the `.env` file have a default value of `changethis`.
|
Some environment variables in the `.env` file have a default value of `changethis`.
|
||||||
@@ -247,11 +255,15 @@ The current Github Actions workflows expect these secrets:
|
|||||||
|
|
||||||
* `DOMAIN_PRODUCTION`
|
* `DOMAIN_PRODUCTION`
|
||||||
* `DOMAIN_STAGING`
|
* `DOMAIN_STAGING`
|
||||||
|
* `STACK_NAME_PRODUCTION`
|
||||||
|
* `STACK_NAME_STAGING`
|
||||||
* `EMAILS_FROM_EMAIL`
|
* `EMAILS_FROM_EMAIL`
|
||||||
* `FIRST_SUPERUSER`
|
* `FIRST_SUPERUSER`
|
||||||
* `FIRST_SUPERUSER_PASSWORD`
|
* `FIRST_SUPERUSER_PASSWORD`
|
||||||
* `POSTGRES_PASSWORD`
|
* `POSTGRES_PASSWORD`
|
||||||
* `SECRET_KEY`
|
* `SECRET_KEY`
|
||||||
|
* `LATEST_CHANGES`
|
||||||
|
* `SMOKESHOW_AUTH_KEY`
|
||||||
|
|
||||||
## GitHub Action Deployment Workflows
|
## GitHub Action Deployment Workflows
|
||||||
|
|
||||||
@@ -288,4 +300,4 @@ Backend API docs: `https://staging.fastapi-project.example.com/docs`
|
|||||||
|
|
||||||
Backend API base URL: `https://staging.fastapi-project.example.com/api/`
|
Backend API base URL: `https://staging.fastapi-project.example.com/api/`
|
||||||
|
|
||||||
Adminer: `https://staging.adminer.fastapi-project.example.com`
|
Adminer: `https://adminer.staging.fastapi-project.example.com`
|
||||||
|
|||||||
+51
-4
@@ -23,6 +23,7 @@ In that case, you will need to use a fake local domain (`dev.example.com`) and m
|
|||||||
If you have a custom domain like that, you need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
|
If you have a custom domain like that, you need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
|
||||||
|
|
||||||
* Open your `hosts` file with administrative privileges using a text editor:
|
* Open your `hosts` file with administrative privileges using a text editor:
|
||||||
|
|
||||||
* **Note for Windows**: If you are in Windows, open the main Windows menu, search for "notepad", right click on it, and select the option "open as Administrator" or similar. Then click the "File" menu, "Open file", go to the directory `c:\Windows\System32\Drivers\etc\`, select the option to show "All files" instead of only "Text (.txt) files", and open the `hosts` file.
|
* **Note for Windows**: If you are in Windows, open the main Windows menu, search for "notepad", right click on it, and select the option "open as Administrator" or similar. Then click the "File" menu, "Open file", go to the directory `c:\Windows\System32\Drivers\etc\`, select the option to show "All files" instead of only "Text (.txt) files", and open the `hosts` file.
|
||||||
* **Note for Mac and Linux**: Your `hosts` file is probably located at `/etc/hosts`, you can edit it in a terminal running `sudo nano /etc/hosts`.
|
* **Note for Mac and Linux**: Your `hosts` file is probably located at `/etc/hosts`, you can edit it in a terminal running `sudo nano /etc/hosts`.
|
||||||
|
|
||||||
@@ -91,6 +92,52 @@ Depending on your workflow, you could want to exclude it from Git, for example i
|
|||||||
|
|
||||||
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
|
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
|
||||||
|
|
||||||
|
### Pre-commits and code linting
|
||||||
|
|
||||||
|
we are using a tool called [pre-commit](https://pre-commit.com/) for code linting and formatting.
|
||||||
|
|
||||||
|
When you install it, it runs right before making a commit in git. This way it ensures that the code is consistent and formatted even before it is committed.
|
||||||
|
|
||||||
|
You can find a file `.pre-commit-config.yaml` with configurations at the root of the project.
|
||||||
|
|
||||||
|
#### Install pre-commit to run automatically
|
||||||
|
|
||||||
|
`pre-commit` is already part of the dependencies of the project, but you could also install it globally if you prefer to, following [the official pre-commit docs](https://pre-commit.com/).
|
||||||
|
|
||||||
|
After having the `pre-commit` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit.
|
||||||
|
|
||||||
|
Using Poetry, you could do it with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
❯ poetry run pre-commit install
|
||||||
|
pre-commit installed at .git/hooks/pre-commit
|
||||||
|
```
|
||||||
|
|
||||||
|
Now whenever you try to commit, e.g. with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git commit
|
||||||
|
```
|
||||||
|
|
||||||
|
...pre-commit will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing.
|
||||||
|
|
||||||
|
Then you can `git add` the modified/fixed files again and now you can commit.
|
||||||
|
|
||||||
|
#### Running pre-commit hooks manually
|
||||||
|
|
||||||
|
you can also run `pre-commit` manually on all the files, you can do it using Poetry with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
❯ poetry run pre-commit run --all-files
|
||||||
|
check for added large files..............................................Passed
|
||||||
|
check toml...............................................................Passed
|
||||||
|
check yaml...............................................................Passed
|
||||||
|
ruff.....................................................................Passed
|
||||||
|
ruff-format..............................................................Passed
|
||||||
|
eslint...................................................................Passed
|
||||||
|
prettier.................................................................Passed
|
||||||
|
```
|
||||||
|
|
||||||
## URLs
|
## URLs
|
||||||
|
|
||||||
The production or staging URLs would use these same paths, but with your own domain.
|
The production or staging URLs would use these same paths, but with your own domain.
|
||||||
@@ -103,9 +150,9 @@ Frontend: http://localhost
|
|||||||
|
|
||||||
Backend: http://localhost/api/
|
Backend: http://localhost/api/
|
||||||
|
|
||||||
Automatic Interactive Docs (Swagger UI): https://localhost/docs
|
Automatic Interactive Docs (Swagger UI): http://localhost/docs
|
||||||
|
|
||||||
Automatic Alternative Docs (ReDoc): https://localhost/redoc
|
Automatic Alternative Docs (ReDoc): http://localhost/redoc
|
||||||
|
|
||||||
Adminer: http://localhost:8080
|
Adminer: http://localhost:8080
|
||||||
|
|
||||||
@@ -119,9 +166,9 @@ Frontend: http://localhost.tiangolo.com
|
|||||||
|
|
||||||
Backend: http://localhost.tiangolo.com/api/
|
Backend: http://localhost.tiangolo.com/api/
|
||||||
|
|
||||||
Automatic Interactive Docs (Swagger UI): https://localhost.tiangolo.com/docs
|
Automatic Interactive Docs (Swagger UI): http://localhost.tiangolo.com/docs
|
||||||
|
|
||||||
Automatic Alternative Docs (ReDoc): https://localhost.tiangolo.com/redoc
|
Automatic Alternative Docs (ReDoc): http://localhost.tiangolo.com/redoc
|
||||||
|
|
||||||
Adminer: http://localhost.tiangolo.com:8080
|
Adminer: http://localhost.tiangolo.com:8080
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
version: "3.3"
|
|
||||||
services:
|
services:
|
||||||
|
|
||||||
proxy:
|
proxy:
|
||||||
image: traefik:v2.3
|
image: traefik:3.0
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
ports:
|
ports:
|
||||||
@@ -37,6 +36,9 @@ services:
|
|||||||
# Dummy https-redirect middleware that doesn't really redirect, only to
|
# Dummy https-redirect middleware that doesn't really redirect, only to
|
||||||
# allow running it locally
|
# allow running it locally
|
||||||
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false
|
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false
|
||||||
|
networks:
|
||||||
|
- traefik-public
|
||||||
|
- default
|
||||||
|
|
||||||
db:
|
db:
|
||||||
restart: "no"
|
restart: "no"
|
||||||
@@ -60,6 +62,17 @@ services:
|
|||||||
INSTALL_DEV: ${INSTALL_DEV-true}
|
INSTALL_DEV: ${INSTALL_DEV-true}
|
||||||
# command: sleep infinity # Infinite loop to keep container alive doing nothing
|
# command: sleep infinity # Infinite loop to keep container alive doing nothing
|
||||||
command: /start-reload.sh
|
command: /start-reload.sh
|
||||||
|
environment:
|
||||||
|
SMTP_HOST: "mailcatcher"
|
||||||
|
SMTP_PORT: "1025"
|
||||||
|
SMTP_TLS: "false"
|
||||||
|
EMAILS_FROM_EMAIL: "noreply@example.com"
|
||||||
|
|
||||||
|
mailcatcher:
|
||||||
|
image: schickling/mailcatcher
|
||||||
|
ports:
|
||||||
|
- "1080:1080"
|
||||||
|
- "1025:1025"
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
restart: "no"
|
restart: "no"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
services:
|
services:
|
||||||
traefik:
|
traefik:
|
||||||
image: traefik:v2.3
|
image: traefik:3.0
|
||||||
ports:
|
ports:
|
||||||
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS
|
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS
|
||||||
- 80:80
|
- 80:80
|
||||||
|
|||||||
+12
-15
@@ -1,4 +1,3 @@
|
|||||||
version: "3.3"
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
image: postgres:12
|
image: postgres:12
|
||||||
@@ -53,7 +52,6 @@ services:
|
|||||||
- SECRET_KEY=${SECRET_KEY?Variable not set}
|
- SECRET_KEY=${SECRET_KEY?Variable not set}
|
||||||
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
|
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
|
||||||
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
|
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
|
||||||
- USERS_OPEN_REGISTRATION=${USERS_OPEN_REGISTRATION}
|
|
||||||
- SMTP_HOST=${SMTP_HOST}
|
- SMTP_HOST=${SMTP_HOST}
|
||||||
- SMTP_USER=${SMTP_USER}
|
- SMTP_USER=${SMTP_USER}
|
||||||
- SMTP_PASSWORD=${SMTP_PASSWORD}
|
- SMTP_PASSWORD=${SMTP_PASSWORD}
|
||||||
@@ -69,6 +67,7 @@ services:
|
|||||||
context: ./backend
|
context: ./backend
|
||||||
args:
|
args:
|
||||||
INSTALL_DEV: ${INSTALL_DEV-false}
|
INSTALL_DEV: ${INSTALL_DEV-false}
|
||||||
|
platform: linux/amd64 # Patch for M1 Mac
|
||||||
labels:
|
labels:
|
||||||
- traefik.enable=true
|
- traefik.enable=true
|
||||||
- traefik.docker.network=traefik-public
|
- traefik.docker.network=traefik-public
|
||||||
@@ -76,14 +75,20 @@ services:
|
|||||||
|
|
||||||
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
|
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
|
||||||
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`)
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`))
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http
|
||||||
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`)
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`))
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
|
||||||
|
|
||||||
|
# Define Traefik Middleware to handle domain with and without "www" to redirect to only one
|
||||||
|
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.regex=^http(s)?://www.(${DOMAIN?Variable not set})/(.*)
|
||||||
|
# Redirect a domain with www to non-www
|
||||||
|
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
|
||||||
|
|
||||||
|
# Enable www redirection for HTTP and HTTPS
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
||||||
|
|
||||||
@@ -105,24 +110,16 @@ services:
|
|||||||
|
|
||||||
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
|
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
|
||||||
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http
|
||||||
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
|
||||||
|
|
||||||
# Handle domain with and without "www" to redirect to only one
|
# Enable www redirection for HTTP and HTTPS
|
||||||
# To disable www redirection remove the next line
|
|
||||||
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.regex=^http(s)?://www.(${DOMAIN?Variable not set})/(.*)
|
|
||||||
# Redirect a domain with www to non-www
|
|
||||||
# To disable it remove the next line
|
|
||||||
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
|
|
||||||
# Middleware to redirect www, to disable it remove the next line
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
|
||||||
# Middleware to redirect www, and redirect HTTP to HTTPS
|
|
||||||
# to disable www redirection remove the section: ${STACK_NAME?Variable not set}-www-redirect,
|
|
||||||
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
|
||||||
volumes:
|
volumes:
|
||||||
app-db-data:
|
app-db-data:
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: { browser: true, es2020: true },
|
|
||||||
extends: [
|
|
||||||
'eslint:recommended',
|
|
||||||
'plugin:@typescript-eslint/recommended',
|
|
||||||
'plugin:react-hooks/recommended',
|
|
||||||
],
|
|
||||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
|
||||||
parser: '@typescript-eslint/parser',
|
|
||||||
plugins: ['react-refresh'],
|
|
||||||
rules: {
|
|
||||||
'react-refresh/only-export-components': [
|
|
||||||
'warn',
|
|
||||||
{ allowConstantExport: true },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -23,3 +23,7 @@ openapi.json
|
|||||||
*.njsproj
|
*.njsproj
|
||||||
*.sln
|
*.sln
|
||||||
*.sw?
|
*.sw?
|
||||||
|
/test-results/
|
||||||
|
/playwright-report/
|
||||||
|
/blob-report/
|
||||||
|
/playwright/.cache/
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
18.x.x
|
20
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
src/client/
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"bracketSpacing": true,
|
|
||||||
"semi": false,
|
|
||||||
"singleQuote": true,
|
|
||||||
"trailingComma": "all",
|
|
||||||
"printWidth": 80,
|
|
||||||
"tabWidth": 2
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
|
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
|
||||||
FROM node:20 as build-stage
|
FROM node:20 AS build-stage
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
@@ -115,3 +115,33 @@ The frontend code is structured as follows:
|
|||||||
* `frontend/src/hooks` - Custom hooks.
|
* `frontend/src/hooks` - Custom hooks.
|
||||||
* `frontend/src/routes` - The different routes of the frontend which include the pages.
|
* `frontend/src/routes` - The different routes of the frontend which include the pages.
|
||||||
* `theme.tsx` - The Chakra UI custom theme.
|
* `theme.tsx` - The Chakra UI custom theme.
|
||||||
|
|
||||||
|
## End-to-End Testing with Playwright
|
||||||
|
|
||||||
|
The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, you can run the tests with the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx playwright test
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also run your tests in UI mode to see the browser and interact with it running:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx playwright test --ui
|
||||||
|
```
|
||||||
|
|
||||||
|
To stop and remove the Docker Compose stack and clean the data created in tests, use the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed.
|
||||||
|
|
||||||
|
For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro).
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
|
||||||
|
"organizeImports": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"ignore": [
|
||||||
|
"node_modules",
|
||||||
|
"src/client/",
|
||||||
|
"src/routeTree.gen.ts",
|
||||||
|
"playwright.config.ts",
|
||||||
|
"playwright-report"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"linter": {
|
||||||
|
"enabled": true,
|
||||||
|
"rules": {
|
||||||
|
"recommended": true,
|
||||||
|
"suspicious": {
|
||||||
|
"noExplicitAny": "off",
|
||||||
|
"noArrayIndexKey": "off"
|
||||||
|
},
|
||||||
|
"style": {
|
||||||
|
"noNonNullAssertion": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"formatter": {
|
||||||
|
"indentStyle": "space"
|
||||||
|
},
|
||||||
|
"javascript": {
|
||||||
|
"formatter": {
|
||||||
|
"quoteStyle": "double",
|
||||||
|
"semicolons": "asNeeded"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Full Stack FastAPI Project</title>
|
<title>Full Stack FastAPI Project</title>
|
||||||
<link rel="icon" type="image/x-icon" href="./src/assets/images/favicon.png" />
|
<link rel="icon" type="image/x-icon" href="/assets/images/favicon.png" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -1,29 +1,36 @@
|
|||||||
import * as fs from "fs";
|
import * as fs from "node:fs"
|
||||||
|
|
||||||
const filePath = "./openapi.json";
|
async function modifyOpenAPIFile(filePath) {
|
||||||
|
try {
|
||||||
|
const data = await fs.promises.readFile(filePath)
|
||||||
|
const openapiContent = JSON.parse(data)
|
||||||
|
|
||||||
fs.readFile(filePath, (err, data) => {
|
const paths = openapiContent.paths
|
||||||
const openapiContent = JSON.parse(data);
|
for (const pathKey of Object.keys(paths)) {
|
||||||
if (err) throw err;
|
const pathData = paths[pathKey]
|
||||||
|
for (const method of Object.keys(pathData)) {
|
||||||
const paths = openapiContent.paths;
|
const operation = pathData[method]
|
||||||
|
if (operation.tags && operation.tags.length > 0) {
|
||||||
Object.keys(paths).forEach((pathKey) => {
|
const tag = operation.tags[0]
|
||||||
const pathData = paths[pathKey];
|
const operationId = operation.operationId
|
||||||
Object.keys(pathData).forEach((method) => {
|
const toRemove = `${tag}-`
|
||||||
const operation = pathData[method];
|
if (operationId.startsWith(toRemove)) {
|
||||||
if (operation.tags && operation.tags.length > 0) {
|
const newOperationId = operationId.substring(toRemove.length)
|
||||||
const tag = operation.tags[0];
|
operation.operationId = newOperationId
|
||||||
const operationId = operation.operationId;
|
}
|
||||||
const toRemove = `${tag}-`;
|
|
||||||
if (operationId.startsWith(toRemove)) {
|
|
||||||
const newOperationId = operationId.substring(toRemove.length);
|
|
||||||
operation.operationId = newOperationId;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
});
|
|
||||||
fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
|
await fs.promises.writeFile(
|
||||||
if (err) throw err;
|
filePath,
|
||||||
});
|
JSON.stringify(openapiContent, null, 2),
|
||||||
});
|
)
|
||||||
|
console.log("File successfully modified")
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const filePath = "./openapi.json"
|
||||||
|
modifyOpenAPIFile(filePath)
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ server {
|
|||||||
location / {
|
location / {
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html index.htm;
|
index index.html index.htm;
|
||||||
try_files $uri $uri/ /index.html =404;
|
try_files $uri /index.html =404;
|
||||||
}
|
}
|
||||||
|
|
||||||
include /etc/nginx/extra-conf.d/*.conf;
|
include /etc/nginx/extra-conf.d/*.conf;
|
||||||
|
|||||||
Generated
+490
-2878
File diff suppressed because it is too large
Load Diff
+12
-15
@@ -6,42 +6,39 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc && vite build",
|
||||||
"lint": "eslint ./src --ext .ts,.tsx --fix",
|
"lint": "biome check --apply-unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./",
|
||||||
"format": "prettier --write ./src/**/*.{ts,tsx,js,jsx,json,md} --ignore-path .prettierignore",
|
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"generate-client": "openapi --input ./openapi.json --useOptions --useUnionTypes --output ./src/client --client axios --exportSchemas true"
|
"generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios --exportSchemas true && biome format --write ./src/client"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@chakra-ui/icons": "2.1.1",
|
"@chakra-ui/icons": "2.1.1",
|
||||||
"@chakra-ui/react": "2.8.2",
|
"@chakra-ui/react": "2.8.2",
|
||||||
"@emotion/react": "11.11.3",
|
"@emotion/react": "11.11.3",
|
||||||
"@emotion/styled": "11.11.0",
|
"@emotion/styled": "11.11.0",
|
||||||
|
"@tanstack/react-query": "^5.28.14",
|
||||||
|
"@tanstack/react-query-devtools": "^5.28.14",
|
||||||
"@tanstack/react-router": "1.19.1",
|
"@tanstack/react-router": "1.19.1",
|
||||||
"axios": "1.6.2",
|
"axios": "1.6.2",
|
||||||
"form-data": "4.0.0",
|
"form-data": "4.0.0",
|
||||||
"framer-motion": "10.16.16",
|
"framer-motion": "10.16.16",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
|
"react-error-boundary": "^4.0.13",
|
||||||
"react-hook-form": "7.49.3",
|
"react-hook-form": "7.49.3",
|
||||||
"react-icons": "5.0.1",
|
"react-icons": "5.0.1"
|
||||||
"react-query": "3.39.3",
|
|
||||||
"zustand": "4.5.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@biomejs/biome": "1.6.1",
|
||||||
|
"@hey-api/openapi-ts": "^0.34.1",
|
||||||
|
"@playwright/test": "^1.45.2",
|
||||||
"@tanstack/router-devtools": "1.19.1",
|
"@tanstack/router-devtools": "1.19.1",
|
||||||
"@tanstack/router-vite-plugin": "1.19.0",
|
"@tanstack/router-vite-plugin": "1.19.0",
|
||||||
"@types/node": "20.10.5",
|
"@types/node": "^20.10.5",
|
||||||
"@types/react": "^18.2.37",
|
"@types/react": "^18.2.37",
|
||||||
"@types/react-dom": "^18.2.15",
|
"@types/react-dom": "^18.2.15",
|
||||||
"@typescript-eslint/eslint-plugin": "^6.10.0",
|
|
||||||
"@typescript-eslint/parser": "^6.10.0",
|
|
||||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||||
"eslint": "^8.53.0",
|
"dotenv": "^16.4.5",
|
||||||
"eslint-plugin-react-hooks": "^4.6.0",
|
|
||||||
"eslint-plugin-react-refresh": "^0.4.4",
|
|
||||||
"openapi-typescript-codegen": "0.25.0",
|
|
||||||
"prettier": "3.2.5",
|
|
||||||
"typescript": "^5.2.2",
|
"typescript": "^5.2.2",
|
||||||
"vite": "^5.0.12"
|
"vite": "^5.0.13"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read environment variables from file.
|
||||||
|
* https://github.com/motdotla/dotenv
|
||||||
|
*/
|
||||||
|
// require('dotenv').config();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* See https://playwright.dev/docs/test-configuration.
|
||||||
|
*/
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './tests',
|
||||||
|
/* Run tests in files in parallel */
|
||||||
|
fullyParallel: true,
|
||||||
|
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
/* Retry on CI only */
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
/* Opt out of parallel tests on CI. */
|
||||||
|
workers: process.env.CI ? 1 : undefined,
|
||||||
|
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||||
|
reporter: 'html',
|
||||||
|
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||||
|
use: {
|
||||||
|
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||||
|
baseURL: 'http://localhost:5173',
|
||||||
|
|
||||||
|
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||||
|
trace: 'on-first-retry',
|
||||||
|
},
|
||||||
|
|
||||||
|
/* Configure projects for major browsers */
|
||||||
|
projects: [
|
||||||
|
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
|
||||||
|
|
||||||
|
{
|
||||||
|
name: 'chromium',
|
||||||
|
use: {
|
||||||
|
...devices['Desktop Chrome'],
|
||||||
|
storageState: 'playwright/.auth/user.json',
|
||||||
|
},
|
||||||
|
dependencies: ['setup'],
|
||||||
|
},
|
||||||
|
|
||||||
|
// {
|
||||||
|
// name: 'firefox',
|
||||||
|
// use: {
|
||||||
|
// ...devices['Desktop Firefox'],
|
||||||
|
// storageState: 'playwright/.auth/user.json',
|
||||||
|
// },
|
||||||
|
// dependencies: ['setup'],
|
||||||
|
// },
|
||||||
|
|
||||||
|
// {
|
||||||
|
// name: 'webkit',
|
||||||
|
// use: {
|
||||||
|
// ...devices['Desktop Safari'],
|
||||||
|
// storageState: 'playwright/.auth/user.json',
|
||||||
|
// },
|
||||||
|
// dependencies: ['setup'],
|
||||||
|
// },
|
||||||
|
|
||||||
|
/* Test against mobile viewports. */
|
||||||
|
// {
|
||||||
|
// name: 'Mobile Chrome',
|
||||||
|
// use: { ...devices['Pixel 5'] },
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// name: 'Mobile Safari',
|
||||||
|
// use: { ...devices['iPhone 12'] },
|
||||||
|
// },
|
||||||
|
|
||||||
|
/* Test against branded browsers. */
|
||||||
|
// {
|
||||||
|
// name: 'Microsoft Edge',
|
||||||
|
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// name: 'Google Chrome',
|
||||||
|
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
|
||||||
|
// },
|
||||||
|
],
|
||||||
|
|
||||||
|
/* Run your local dev server before starting the tests */
|
||||||
|
webServer: {
|
||||||
|
command: 'npm run dev',
|
||||||
|
url: 'http://localhost:5173',
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
Before Width: | Height: | Size: 6.2 KiB After Width: | Height: | Size: 6.2 KiB |
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 4.9 KiB |
@@ -1,25 +1,25 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
import type { ApiRequestOptions } from "./ApiRequestOptions"
|
||||||
/* istanbul ignore file */
|
import type { ApiResult } from "./ApiResult"
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
import type { ApiRequestOptions } from './ApiRequestOptions';
|
|
||||||
import type { ApiResult } from './ApiResult';
|
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
public readonly url: string;
|
public readonly url: string
|
||||||
public readonly status: number;
|
public readonly status: number
|
||||||
public readonly statusText: string;
|
public readonly statusText: string
|
||||||
public readonly body: any;
|
public readonly body: unknown
|
||||||
public readonly request: ApiRequestOptions;
|
public readonly request: ApiRequestOptions
|
||||||
|
|
||||||
constructor(request: ApiRequestOptions, response: ApiResult, message: string) {
|
constructor(
|
||||||
super(message);
|
request: ApiRequestOptions,
|
||||||
|
response: ApiResult,
|
||||||
|
message: string,
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
|
||||||
this.name = 'ApiError';
|
this.name = "ApiError"
|
||||||
this.url = response.url;
|
this.url = response.url
|
||||||
this.status = response.status;
|
this.status = response.status
|
||||||
this.statusText = response.statusText;
|
this.statusText = response.statusText
|
||||||
this.body = response.body;
|
this.body = response.body
|
||||||
this.request = request;
|
this.request = request
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export type ApiRequestOptions = {
|
export type ApiRequestOptions = {
|
||||||
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
|
readonly method:
|
||||||
readonly url: string;
|
| "GET"
|
||||||
readonly path?: Record<string, any>;
|
| "PUT"
|
||||||
readonly cookies?: Record<string, any>;
|
| "POST"
|
||||||
readonly headers?: Record<string, any>;
|
| "DELETE"
|
||||||
readonly query?: Record<string, any>;
|
| "OPTIONS"
|
||||||
readonly formData?: Record<string, any>;
|
| "HEAD"
|
||||||
readonly body?: any;
|
| "PATCH"
|
||||||
readonly mediaType?: string;
|
readonly url: string
|
||||||
readonly responseHeader?: string;
|
readonly path?: Record<string, unknown>
|
||||||
readonly errors?: Record<number, string>;
|
readonly cookies?: Record<string, unknown>
|
||||||
};
|
readonly headers?: Record<string, unknown>
|
||||||
|
readonly query?: Record<string, unknown>
|
||||||
|
readonly formData?: Record<string, unknown>
|
||||||
|
readonly body?: any
|
||||||
|
readonly mediaType?: string
|
||||||
|
readonly responseHeader?: string
|
||||||
|
readonly errors?: Record<number, string>
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
export type ApiResult<TData = any> = {
|
||||||
/* istanbul ignore file */
|
readonly body: TData
|
||||||
/* tslint:disable */
|
readonly ok: boolean
|
||||||
/* eslint-disable */
|
readonly status: number
|
||||||
export type ApiResult = {
|
readonly statusText: string
|
||||||
readonly url: string;
|
readonly url: string
|
||||||
readonly ok: boolean;
|
}
|
||||||
readonly status: number;
|
|
||||||
readonly statusText: string;
|
|
||||||
readonly body: any;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,131 +1,126 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export class CancelError extends Error {
|
export class CancelError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message)
|
||||||
|
this.name = "CancelError"
|
||||||
|
}
|
||||||
|
|
||||||
constructor(message: string) {
|
public get isCancelled(): boolean {
|
||||||
super(message);
|
return true
|
||||||
this.name = 'CancelError';
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public get isCancelled(): boolean {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OnCancel {
|
export interface OnCancel {
|
||||||
readonly isResolved: boolean;
|
readonly isResolved: boolean
|
||||||
readonly isRejected: boolean;
|
readonly isRejected: boolean
|
||||||
readonly isCancelled: boolean;
|
readonly isCancelled: boolean
|
||||||
|
|
||||||
(cancelHandler: () => void): void;
|
(cancelHandler: () => void): void
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CancelablePromise<T> implements Promise<T> {
|
export class CancelablePromise<T> implements Promise<T> {
|
||||||
#isResolved: boolean;
|
private _isResolved: boolean
|
||||||
#isRejected: boolean;
|
private _isRejected: boolean
|
||||||
#isCancelled: boolean;
|
private _isCancelled: boolean
|
||||||
readonly #cancelHandlers: (() => void)[];
|
readonly cancelHandlers: (() => void)[]
|
||||||
readonly #promise: Promise<T>;
|
readonly promise: Promise<T>
|
||||||
#resolve?: (value: T | PromiseLike<T>) => void;
|
private _resolve?: (value: T | PromiseLike<T>) => void
|
||||||
#reject?: (reason?: any) => void;
|
private _reject?: (reason?: unknown) => void
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
executor: (
|
executor: (
|
||||||
resolve: (value: T | PromiseLike<T>) => void,
|
resolve: (value: T | PromiseLike<T>) => void,
|
||||||
reject: (reason?: any) => void,
|
reject: (reason?: unknown) => void,
|
||||||
onCancel: OnCancel
|
onCancel: OnCancel,
|
||||||
) => void
|
) => void,
|
||||||
) {
|
) {
|
||||||
this.#isResolved = false;
|
this._isResolved = false
|
||||||
this.#isRejected = false;
|
this._isRejected = false
|
||||||
this.#isCancelled = false;
|
this._isCancelled = false
|
||||||
this.#cancelHandlers = [];
|
this.cancelHandlers = []
|
||||||
this.#promise = new Promise<T>((resolve, reject) => {
|
this.promise = new Promise<T>((resolve, reject) => {
|
||||||
this.#resolve = resolve;
|
this._resolve = resolve
|
||||||
this.#reject = reject;
|
this._reject = reject
|
||||||
|
|
||||||
const onResolve = (value: T | PromiseLike<T>): void => {
|
const onResolve = (value: T | PromiseLike<T>): void => {
|
||||||
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
|
if (this._isResolved || this._isRejected || this._isCancelled) {
|
||||||
return;
|
return
|
||||||
}
|
|
||||||
this.#isResolved = true;
|
|
||||||
this.#resolve?.(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onReject = (reason?: any): void => {
|
|
||||||
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.#isRejected = true;
|
|
||||||
this.#reject?.(reason);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onCancel = (cancelHandler: () => void): void => {
|
|
||||||
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.#cancelHandlers.push(cancelHandler);
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.defineProperty(onCancel, 'isResolved', {
|
|
||||||
get: (): boolean => this.#isResolved,
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(onCancel, 'isRejected', {
|
|
||||||
get: (): boolean => this.#isRejected,
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(onCancel, 'isCancelled', {
|
|
||||||
get: (): boolean => this.#isCancelled,
|
|
||||||
});
|
|
||||||
|
|
||||||
return executor(onResolve, onReject, onCancel as OnCancel);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
get [Symbol.toStringTag]() {
|
|
||||||
return "Cancellable Promise";
|
|
||||||
}
|
|
||||||
|
|
||||||
public then<TResult1 = T, TResult2 = never>(
|
|
||||||
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
|
|
||||||
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
|
|
||||||
): Promise<TResult1 | TResult2> {
|
|
||||||
return this.#promise.then(onFulfilled, onRejected);
|
|
||||||
}
|
|
||||||
|
|
||||||
public catch<TResult = never>(
|
|
||||||
onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
|
|
||||||
): Promise<T | TResult> {
|
|
||||||
return this.#promise.catch(onRejected);
|
|
||||||
}
|
|
||||||
|
|
||||||
public finally(onFinally?: (() => void) | null): Promise<T> {
|
|
||||||
return this.#promise.finally(onFinally);
|
|
||||||
}
|
|
||||||
|
|
||||||
public cancel(): void {
|
|
||||||
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
this.#isCancelled = true;
|
this._isResolved = true
|
||||||
if (this.#cancelHandlers.length) {
|
if (this._resolve) this._resolve(value)
|
||||||
try {
|
}
|
||||||
for (const cancelHandler of this.#cancelHandlers) {
|
|
||||||
cancelHandler();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Cancellation threw an error', error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.#cancelHandlers.length = 0;
|
|
||||||
this.#reject?.(new CancelError('Request aborted'));
|
|
||||||
}
|
|
||||||
|
|
||||||
public get isCancelled(): boolean {
|
const onReject = (reason?: unknown): void => {
|
||||||
return this.#isCancelled;
|
if (this._isResolved || this._isRejected || this._isCancelled) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this._isRejected = true
|
||||||
|
if (this._reject) this._reject(reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onCancel = (cancelHandler: () => void): void => {
|
||||||
|
if (this._isResolved || this._isRejected || this._isCancelled) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.cancelHandlers.push(cancelHandler)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.defineProperty(onCancel, "isResolved", {
|
||||||
|
get: (): boolean => this._isResolved,
|
||||||
|
})
|
||||||
|
|
||||||
|
Object.defineProperty(onCancel, "isRejected", {
|
||||||
|
get: (): boolean => this._isRejected,
|
||||||
|
})
|
||||||
|
|
||||||
|
Object.defineProperty(onCancel, "isCancelled", {
|
||||||
|
get: (): boolean => this._isCancelled,
|
||||||
|
})
|
||||||
|
|
||||||
|
return executor(onResolve, onReject, onCancel as OnCancel)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
get [Symbol.toStringTag]() {
|
||||||
|
return "Cancellable Promise"
|
||||||
|
}
|
||||||
|
|
||||||
|
public then<TResult1 = T, TResult2 = never>(
|
||||||
|
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
|
||||||
|
onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
|
||||||
|
): Promise<TResult1 | TResult2> {
|
||||||
|
return this.promise.then(onFulfilled, onRejected)
|
||||||
|
}
|
||||||
|
|
||||||
|
public catch<TResult = never>(
|
||||||
|
onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
|
||||||
|
): Promise<T | TResult> {
|
||||||
|
return this.promise.catch(onRejected)
|
||||||
|
}
|
||||||
|
|
||||||
|
public finally(onFinally?: (() => void) | null): Promise<T> {
|
||||||
|
return this.promise.finally(onFinally)
|
||||||
|
}
|
||||||
|
|
||||||
|
public cancel(): void {
|
||||||
|
if (this._isResolved || this._isRejected || this._isCancelled) {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
this._isCancelled = true
|
||||||
|
if (this.cancelHandlers.length) {
|
||||||
|
try {
|
||||||
|
for (const cancelHandler of this.cancelHandlers) {
|
||||||
|
cancelHandler()
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("Cancellation threw an error", error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.cancelHandlers.length = 0
|
||||||
|
if (this._reject) this._reject(new CancelError("Request aborted"))
|
||||||
|
}
|
||||||
|
|
||||||
|
public get isCancelled(): boolean {
|
||||||
|
return this._isCancelled
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,57 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
import type { AxiosRequestConfig, AxiosResponse } from "axios"
|
||||||
/* istanbul ignore file */
|
import type { ApiRequestOptions } from "./ApiRequestOptions"
|
||||||
/* tslint:disable */
|
import type { TResult } from "./types"
|
||||||
/* eslint-disable */
|
|
||||||
import type { ApiRequestOptions } from './ApiRequestOptions';
|
|
||||||
|
|
||||||
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
|
type Headers = Record<string, string>
|
||||||
type Headers = Record<string, string>;
|
type Middleware<T> = (value: T) => T | Promise<T>
|
||||||
|
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
|
||||||
|
|
||||||
|
export class Interceptors<T> {
|
||||||
|
_fns: Middleware<T>[]
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this._fns = []
|
||||||
|
}
|
||||||
|
|
||||||
|
eject(fn: Middleware<T>) {
|
||||||
|
const index = this._fns.indexOf(fn)
|
||||||
|
if (index !== -1) {
|
||||||
|
this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use(fn: Middleware<T>) {
|
||||||
|
this._fns = [...this._fns, fn]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type OpenAPIConfig = {
|
export type OpenAPIConfig = {
|
||||||
BASE: string;
|
BASE: string
|
||||||
VERSION: string;
|
CREDENTIALS: "include" | "omit" | "same-origin"
|
||||||
WITH_CREDENTIALS: boolean;
|
ENCODE_PATH?: ((path: string) => string) | undefined
|
||||||
CREDENTIALS: 'include' | 'omit' | 'same-origin';
|
HEADERS?: Headers | Resolver<Headers> | undefined
|
||||||
TOKEN?: string | Resolver<string> | undefined;
|
PASSWORD?: string | Resolver<string> | undefined
|
||||||
USERNAME?: string | Resolver<string> | undefined;
|
RESULT?: TResult
|
||||||
PASSWORD?: string | Resolver<string> | undefined;
|
TOKEN?: string | Resolver<string> | undefined
|
||||||
HEADERS?: Headers | Resolver<Headers> | undefined;
|
USERNAME?: string | Resolver<string> | undefined
|
||||||
ENCODE_PATH?: ((path: string) => string) | undefined;
|
VERSION: string
|
||||||
};
|
WITH_CREDENTIALS: boolean
|
||||||
|
interceptors: {
|
||||||
|
request: Interceptors<AxiosRequestConfig>
|
||||||
|
response: Interceptors<AxiosResponse>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const OpenAPI: OpenAPIConfig = {
|
export const OpenAPI: OpenAPIConfig = {
|
||||||
BASE: '',
|
BASE: "",
|
||||||
VERSION: '0.1.0',
|
CREDENTIALS: "include",
|
||||||
WITH_CREDENTIALS: false,
|
ENCODE_PATH: undefined,
|
||||||
CREDENTIALS: 'include',
|
HEADERS: undefined,
|
||||||
TOKEN: undefined,
|
PASSWORD: undefined,
|
||||||
USERNAME: undefined,
|
RESULT: "body",
|
||||||
PASSWORD: undefined,
|
TOKEN: undefined,
|
||||||
HEADERS: undefined,
|
USERNAME: undefined,
|
||||||
ENCODE_PATH: undefined,
|
VERSION: "0.1.0",
|
||||||
};
|
WITH_CREDENTIALS: false,
|
||||||
|
interceptors: { request: new Interceptors(), response: new Interceptors() },
|
||||||
|
}
|
||||||
|
|||||||
+324
-267
@@ -1,283 +1,319 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
import axios from "axios"
|
||||||
/* istanbul ignore file */
|
import type {
|
||||||
/* tslint:disable */
|
AxiosError,
|
||||||
/* eslint-disable */
|
AxiosInstance,
|
||||||
import axios from 'axios';
|
AxiosRequestConfig,
|
||||||
import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';
|
AxiosResponse,
|
||||||
import FormData from 'form-data';
|
} from "axios"
|
||||||
|
|
||||||
import { ApiError } from './ApiError';
|
import { ApiError } from "./ApiError"
|
||||||
import type { ApiRequestOptions } from './ApiRequestOptions';
|
import type { ApiRequestOptions } from "./ApiRequestOptions"
|
||||||
import type { ApiResult } from './ApiResult';
|
import type { ApiResult } from "./ApiResult"
|
||||||
import { CancelablePromise } from './CancelablePromise';
|
import { CancelablePromise } from "./CancelablePromise"
|
||||||
import type { OnCancel } from './CancelablePromise';
|
import type { OnCancel } from "./CancelablePromise"
|
||||||
import type { OpenAPIConfig } from './OpenAPI';
|
import type { OpenAPIConfig } from "./OpenAPI"
|
||||||
|
|
||||||
export const isDefined = <T>(value: T | null | undefined): value is Exclude<T, null | undefined> => {
|
export const isString = (value: unknown): value is string => {
|
||||||
return value !== undefined && value !== null;
|
return typeof value === "string"
|
||||||
};
|
}
|
||||||
|
|
||||||
export const isString = (value: any): value is string => {
|
export const isStringWithValue = (value: unknown): value is string => {
|
||||||
return typeof value === 'string';
|
return isString(value) && value !== ""
|
||||||
};
|
}
|
||||||
|
|
||||||
export const isStringWithValue = (value: any): value is string => {
|
|
||||||
return isString(value) && value !== '';
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isBlob = (value: any): value is Blob => {
|
export const isBlob = (value: any): value is Blob => {
|
||||||
return (
|
return value instanceof Blob
|
||||||
typeof value === 'object' &&
|
}
|
||||||
typeof value.type === 'string' &&
|
|
||||||
typeof value.stream === 'function' &&
|
|
||||||
typeof value.arrayBuffer === 'function' &&
|
|
||||||
typeof value.constructor === 'function' &&
|
|
||||||
typeof value.constructor.name === 'string' &&
|
|
||||||
/^(Blob|File)$/.test(value.constructor.name) &&
|
|
||||||
/^(Blob|File)$/.test(value[Symbol.toStringTag])
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isFormData = (value: any): value is FormData => {
|
export const isFormData = (value: unknown): value is FormData => {
|
||||||
return value instanceof FormData;
|
return value instanceof FormData
|
||||||
};
|
}
|
||||||
|
|
||||||
export const isSuccess = (status: number): boolean => {
|
export const isSuccess = (status: number): boolean => {
|
||||||
return status >= 200 && status < 300;
|
return status >= 200 && status < 300
|
||||||
};
|
}
|
||||||
|
|
||||||
export const base64 = (str: string): string => {
|
export const base64 = (str: string): string => {
|
||||||
try {
|
try {
|
||||||
return btoa(str);
|
return btoa(str)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
return Buffer.from(str).toString('base64');
|
return Buffer.from(str).toString("base64")
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const getQueryString = (params: Record<string, any>): string => {
|
export const getQueryString = (params: Record<string, unknown>): string => {
|
||||||
const qs: string[] = [];
|
const qs: string[] = []
|
||||||
|
|
||||||
const append = (key: string, value: any) => {
|
const append = (key: string, value: unknown) => {
|
||||||
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||||
};
|
}
|
||||||
|
|
||||||
const process = (key: string, value: any) => {
|
const encodePair = (key: string, value: unknown) => {
|
||||||
if (isDefined(value)) {
|
if (value === undefined || value === null) {
|
||||||
if (Array.isArray(value)) {
|
return
|
||||||
value.forEach(v => {
|
|
||||||
process(key, v);
|
|
||||||
});
|
|
||||||
} else if (typeof value === 'object') {
|
|
||||||
Object.entries(value).forEach(([k, v]) => {
|
|
||||||
process(`${key}[${k}]`, v);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
append(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.entries(params).forEach(([key, value]) => {
|
|
||||||
process(key, value);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (qs.length > 0) {
|
|
||||||
return `?${qs.join('&')}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return '';
|
if (Array.isArray(value)) {
|
||||||
};
|
value.forEach((v) => encodePair(key, v))
|
||||||
|
} else if (typeof value === "object") {
|
||||||
|
Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v))
|
||||||
|
} else {
|
||||||
|
append(key, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(params).forEach(([key, value]) => encodePair(key, value))
|
||||||
|
|
||||||
|
return qs.length ? `?${qs.join("&")}` : ""
|
||||||
|
}
|
||||||
|
|
||||||
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
|
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
|
||||||
const encoder = config.ENCODE_PATH || encodeURI;
|
const encoder = config.ENCODE_PATH || encodeURI
|
||||||
|
|
||||||
const path = options.url
|
const path = options.url
|
||||||
.replace('{api-version}', config.VERSION)
|
.replace("{api-version}", config.VERSION)
|
||||||
.replace(/{(.*?)}/g, (substring: string, group: string) => {
|
.replace(/{(.*?)}/g, (substring: string, group: string) => {
|
||||||
if (options.path?.hasOwnProperty(group)) {
|
if (options.path?.hasOwnProperty(group)) {
|
||||||
return encoder(String(options.path[group]));
|
return encoder(String(options.path[group]))
|
||||||
}
|
}
|
||||||
return substring;
|
return substring
|
||||||
});
|
|
||||||
|
|
||||||
const url = `${config.BASE}${path}`;
|
|
||||||
if (options.query) {
|
|
||||||
return `${url}${getQueryString(options.query)}`;
|
|
||||||
}
|
|
||||||
return url;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
|
|
||||||
if (options.formData) {
|
|
||||||
const formData = new FormData();
|
|
||||||
|
|
||||||
const process = (key: string, value: any) => {
|
|
||||||
if (isString(value) || isBlob(value)) {
|
|
||||||
formData.append(key, value);
|
|
||||||
} else {
|
|
||||||
formData.append(key, JSON.stringify(value));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.entries(options.formData)
|
|
||||||
.filter(([_, value]) => isDefined(value))
|
|
||||||
.forEach(([key, value]) => {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
value.forEach(v => process(key, v));
|
|
||||||
} else {
|
|
||||||
process(key, value);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return formData;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
|
|
||||||
|
|
||||||
export const resolve = async <T>(options: ApiRequestOptions, resolver?: T | Resolver<T>): Promise<T | undefined> => {
|
|
||||||
if (typeof resolver === 'function') {
|
|
||||||
return (resolver as Resolver<T>)(options);
|
|
||||||
}
|
|
||||||
return resolver;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise<Record<string, string>> => {
|
|
||||||
const token = await resolve(options, config.TOKEN);
|
|
||||||
const username = await resolve(options, config.USERNAME);
|
|
||||||
const password = await resolve(options, config.PASSWORD);
|
|
||||||
const additionalHeaders = await resolve(options, config.HEADERS);
|
|
||||||
const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {}
|
|
||||||
|
|
||||||
const headers = Object.entries({
|
|
||||||
Accept: 'application/json',
|
|
||||||
...additionalHeaders,
|
|
||||||
...options.headers,
|
|
||||||
...formHeaders,
|
|
||||||
})
|
})
|
||||||
.filter(([_, value]) => isDefined(value))
|
|
||||||
.reduce((headers, [key, value]) => ({
|
const url = config.BASE + path
|
||||||
|
return options.query ? url + getQueryString(options.query) : url
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getFormData = (
|
||||||
|
options: ApiRequestOptions,
|
||||||
|
): FormData | undefined => {
|
||||||
|
if (options.formData) {
|
||||||
|
const formData = new FormData()
|
||||||
|
|
||||||
|
const process = (key: string, value: unknown) => {
|
||||||
|
if (isString(value) || isBlob(value)) {
|
||||||
|
formData.append(key, value)
|
||||||
|
} else {
|
||||||
|
formData.append(key, JSON.stringify(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(options.formData)
|
||||||
|
.filter(([, value]) => value !== undefined && value !== null)
|
||||||
|
.forEach(([key, value]) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
value.forEach((v) => process(key, v))
|
||||||
|
} else {
|
||||||
|
process(key, value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return formData
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
|
||||||
|
|
||||||
|
export const resolve = async <T>(
|
||||||
|
options: ApiRequestOptions,
|
||||||
|
resolver?: T | Resolver<T>,
|
||||||
|
): Promise<T | undefined> => {
|
||||||
|
if (typeof resolver === "function") {
|
||||||
|
return (resolver as Resolver<T>)(options)
|
||||||
|
}
|
||||||
|
return resolver
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getHeaders = async (
|
||||||
|
config: OpenAPIConfig,
|
||||||
|
options: ApiRequestOptions,
|
||||||
|
): Promise<Record<string, string>> => {
|
||||||
|
const [token, username, password, additionalHeaders] = await Promise.all([
|
||||||
|
resolve(options, config.TOKEN),
|
||||||
|
resolve(options, config.USERNAME),
|
||||||
|
resolve(options, config.PASSWORD),
|
||||||
|
resolve(options, config.HEADERS),
|
||||||
|
])
|
||||||
|
|
||||||
|
const headers = Object.entries({
|
||||||
|
Accept: "application/json",
|
||||||
|
...additionalHeaders,
|
||||||
|
...options.headers,
|
||||||
|
})
|
||||||
|
.filter(([, value]) => value !== undefined && value !== null)
|
||||||
|
.reduce(
|
||||||
|
(headers, [key, value]) => ({
|
||||||
...headers,
|
...headers,
|
||||||
[key]: String(value),
|
[key]: String(value),
|
||||||
}), {} as Record<string, string>);
|
}),
|
||||||
|
{} as Record<string, string>,
|
||||||
|
)
|
||||||
|
|
||||||
if (isStringWithValue(token)) {
|
if (isStringWithValue(token)) {
|
||||||
headers['Authorization'] = `Bearer ${token}`;
|
headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isStringWithValue(username) && isStringWithValue(password)) {
|
||||||
|
const credentials = base64(`${username}:${password}`)
|
||||||
|
headers.Authorization = `Basic ${credentials}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.body !== undefined) {
|
||||||
|
if (options.mediaType) {
|
||||||
|
headers["Content-Type"] = options.mediaType
|
||||||
|
} else if (isBlob(options.body)) {
|
||||||
|
headers["Content-Type"] = options.body.type || "application/octet-stream"
|
||||||
|
} else if (isString(options.body)) {
|
||||||
|
headers["Content-Type"] = "text/plain"
|
||||||
|
} else if (!isFormData(options.body)) {
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
}
|
}
|
||||||
|
} else if (options.formData !== undefined) {
|
||||||
if (isStringWithValue(username) && isStringWithValue(password)) {
|
if (options.mediaType) {
|
||||||
const credentials = base64(`${username}:${password}`);
|
headers["Content-Type"] = options.mediaType
|
||||||
headers['Authorization'] = `Basic ${credentials}`;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (options.body) {
|
return headers
|
||||||
if (options.mediaType) {
|
}
|
||||||
headers['Content-Type'] = options.mediaType;
|
|
||||||
} else if (isBlob(options.body)) {
|
|
||||||
headers['Content-Type'] = options.body.type || 'application/octet-stream';
|
|
||||||
} else if (isString(options.body)) {
|
|
||||||
headers['Content-Type'] = 'text/plain';
|
|
||||||
} else if (!isFormData(options.body)) {
|
|
||||||
headers['Content-Type'] = 'application/json';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return headers;
|
export const getRequestBody = (options: ApiRequestOptions): unknown => {
|
||||||
};
|
if (options.body) {
|
||||||
|
return options.body
|
||||||
export const getRequestBody = (options: ApiRequestOptions): any => {
|
}
|
||||||
if (options.body) {
|
return undefined
|
||||||
return options.body;
|
}
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const sendRequest = async <T>(
|
export const sendRequest = async <T>(
|
||||||
config: OpenAPIConfig,
|
config: OpenAPIConfig,
|
||||||
options: ApiRequestOptions,
|
options: ApiRequestOptions,
|
||||||
url: string,
|
url: string,
|
||||||
body: any,
|
body: unknown,
|
||||||
formData: FormData | undefined,
|
formData: FormData | undefined,
|
||||||
headers: Record<string, string>,
|
headers: Record<string, string>,
|
||||||
onCancel: OnCancel,
|
onCancel: OnCancel,
|
||||||
axiosClient: AxiosInstance
|
axiosClient: AxiosInstance,
|
||||||
): Promise<AxiosResponse<T>> => {
|
): Promise<AxiosResponse<T>> => {
|
||||||
const source = axios.CancelToken.source();
|
const controller = new AbortController()
|
||||||
|
|
||||||
const requestConfig: AxiosRequestConfig = {
|
let requestConfig: AxiosRequestConfig = {
|
||||||
url,
|
data: body ?? formData,
|
||||||
headers,
|
headers,
|
||||||
data: body ?? formData,
|
method: options.method,
|
||||||
method: options.method,
|
signal: controller.signal,
|
||||||
withCredentials: config.WITH_CREDENTIALS,
|
url,
|
||||||
cancelToken: source.token,
|
withCredentials: config.WITH_CREDENTIALS,
|
||||||
};
|
}
|
||||||
|
|
||||||
onCancel(() => source.cancel('The user aborted a request.'));
|
onCancel(() => controller.abort())
|
||||||
|
|
||||||
try {
|
for (const fn of config.interceptors.request._fns) {
|
||||||
return await axiosClient.request(requestConfig);
|
requestConfig = await fn(requestConfig)
|
||||||
} catch (error) {
|
}
|
||||||
const axiosError = error as AxiosError<T>;
|
|
||||||
if (axiosError.response) {
|
try {
|
||||||
return axiosError.response;
|
return await axiosClient.request(requestConfig)
|
||||||
}
|
} catch (error) {
|
||||||
throw error;
|
const axiosError = error as AxiosError<T>
|
||||||
|
if (axiosError.response) {
|
||||||
|
return axiosError.response
|
||||||
}
|
}
|
||||||
};
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const getResponseHeader = (response: AxiosResponse<any>, responseHeader?: string): string | undefined => {
|
export const getResponseHeader = (
|
||||||
if (responseHeader) {
|
response: AxiosResponse<unknown>,
|
||||||
const content = response.headers[responseHeader];
|
responseHeader?: string,
|
||||||
if (isString(content)) {
|
): string | undefined => {
|
||||||
return content;
|
if (responseHeader) {
|
||||||
}
|
const content = response.headers[responseHeader]
|
||||||
|
if (isString(content)) {
|
||||||
|
return content
|
||||||
}
|
}
|
||||||
return undefined;
|
}
|
||||||
};
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
export const getResponseBody = (response: AxiosResponse<any>): any => {
|
export const getResponseBody = (response: AxiosResponse<unknown>): unknown => {
|
||||||
if (response.status !== 204) {
|
if (response.status !== 204) {
|
||||||
return response.data;
|
return response.data
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined
|
||||||
};
|
}
|
||||||
|
|
||||||
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {
|
export const catchErrorCodes = (
|
||||||
const errors: Record<number, string> = {
|
options: ApiRequestOptions,
|
||||||
400: 'Bad Request',
|
result: ApiResult,
|
||||||
401: 'Unauthorized',
|
): void => {
|
||||||
403: 'Forbidden',
|
const errors: Record<number, string> = {
|
||||||
404: 'Not Found',
|
400: "Bad Request",
|
||||||
500: 'Internal Server Error',
|
401: "Unauthorized",
|
||||||
502: 'Bad Gateway',
|
402: "Payment Required",
|
||||||
503: 'Service Unavailable',
|
403: "Forbidden",
|
||||||
...options.errors,
|
404: "Not Found",
|
||||||
}
|
405: "Method Not Allowed",
|
||||||
|
406: "Not Acceptable",
|
||||||
|
407: "Proxy Authentication Required",
|
||||||
|
408: "Request Timeout",
|
||||||
|
409: "Conflict",
|
||||||
|
410: "Gone",
|
||||||
|
411: "Length Required",
|
||||||
|
412: "Precondition Failed",
|
||||||
|
413: "Payload Too Large",
|
||||||
|
414: "URI Too Long",
|
||||||
|
415: "Unsupported Media Type",
|
||||||
|
416: "Range Not Satisfiable",
|
||||||
|
417: "Expectation Failed",
|
||||||
|
418: "Im a teapot",
|
||||||
|
421: "Misdirected Request",
|
||||||
|
422: "Unprocessable Content",
|
||||||
|
423: "Locked",
|
||||||
|
424: "Failed Dependency",
|
||||||
|
425: "Too Early",
|
||||||
|
426: "Upgrade Required",
|
||||||
|
428: "Precondition Required",
|
||||||
|
429: "Too Many Requests",
|
||||||
|
431: "Request Header Fields Too Large",
|
||||||
|
451: "Unavailable For Legal Reasons",
|
||||||
|
500: "Internal Server Error",
|
||||||
|
501: "Not Implemented",
|
||||||
|
502: "Bad Gateway",
|
||||||
|
503: "Service Unavailable",
|
||||||
|
504: "Gateway Timeout",
|
||||||
|
505: "HTTP Version Not Supported",
|
||||||
|
506: "Variant Also Negotiates",
|
||||||
|
507: "Insufficient Storage",
|
||||||
|
508: "Loop Detected",
|
||||||
|
510: "Not Extended",
|
||||||
|
511: "Network Authentication Required",
|
||||||
|
...options.errors,
|
||||||
|
}
|
||||||
|
|
||||||
const error = errors[result.status];
|
const error = errors[result.status]
|
||||||
if (error) {
|
if (error) {
|
||||||
throw new ApiError(options, result, error);
|
throw new ApiError(options, result, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
const errorStatus = result.status ?? 'unknown';
|
const errorStatus = result.status ?? "unknown"
|
||||||
const errorStatusText = result.statusText ?? 'unknown';
|
const errorStatusText = result.statusText ?? "unknown"
|
||||||
const errorBody = (() => {
|
const errorBody = (() => {
|
||||||
try {
|
try {
|
||||||
return JSON.stringify(result.body, null, 2);
|
return JSON.stringify(result.body, null, 2)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return undefined;
|
return undefined
|
||||||
}
|
}
|
||||||
})();
|
})()
|
||||||
|
|
||||||
throw new ApiError(options, result,
|
throw new ApiError(
|
||||||
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
|
options,
|
||||||
);
|
result,
|
||||||
}
|
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`,
|
||||||
};
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request method
|
* Request method
|
||||||
@@ -287,33 +323,54 @@ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult):
|
|||||||
* @returns CancelablePromise<T>
|
* @returns CancelablePromise<T>
|
||||||
* @throws ApiError
|
* @throws ApiError
|
||||||
*/
|
*/
|
||||||
export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<T> => {
|
export const request = <T>(
|
||||||
return new CancelablePromise(async (resolve, reject, onCancel) => {
|
config: OpenAPIConfig,
|
||||||
try {
|
options: ApiRequestOptions,
|
||||||
const url = getUrl(config, options);
|
axiosClient: AxiosInstance = axios,
|
||||||
const formData = getFormData(options);
|
): CancelablePromise<T> => {
|
||||||
const body = getRequestBody(options);
|
return new CancelablePromise(async (resolve, reject, onCancel) => {
|
||||||
const headers = await getHeaders(config, options, formData);
|
try {
|
||||||
|
const url = getUrl(config, options)
|
||||||
|
const formData = getFormData(options)
|
||||||
|
const body = getRequestBody(options)
|
||||||
|
const headers = await getHeaders(config, options)
|
||||||
|
|
||||||
if (!onCancel.isCancelled) {
|
if (!onCancel.isCancelled) {
|
||||||
const response = await sendRequest<T>(config, options, url, body, formData, headers, onCancel, axiosClient);
|
let response = await sendRequest<T>(
|
||||||
const responseBody = getResponseBody(response);
|
config,
|
||||||
const responseHeader = getResponseHeader(response, options.responseHeader);
|
options,
|
||||||
|
url,
|
||||||
|
body,
|
||||||
|
formData,
|
||||||
|
headers,
|
||||||
|
onCancel,
|
||||||
|
axiosClient,
|
||||||
|
)
|
||||||
|
|
||||||
const result: ApiResult = {
|
for (const fn of config.interceptors.response._fns) {
|
||||||
url,
|
response = await fn(response)
|
||||||
ok: isSuccess(response.status),
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
body: responseHeader ?? responseBody,
|
|
||||||
};
|
|
||||||
|
|
||||||
catchErrorCodes(options, result);
|
|
||||||
|
|
||||||
resolve(result.body);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
};
|
const responseBody = getResponseBody(response)
|
||||||
|
const responseHeader = getResponseHeader(
|
||||||
|
response,
|
||||||
|
options.responseHeader,
|
||||||
|
)
|
||||||
|
|
||||||
|
const result: ApiResult = {
|
||||||
|
url,
|
||||||
|
ok: isSuccess(response.status),
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
body: responseHeader ?? responseBody,
|
||||||
|
}
|
||||||
|
|
||||||
|
catchErrorCodes(options, result)
|
||||||
|
|
||||||
|
resolve(result.body)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
reject(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { ApiResult } from "./ApiResult"
|
||||||
|
|
||||||
|
export type TResult = "body" | "raw"
|
||||||
|
|
||||||
|
export type TApiResponse<T extends TResult, TData> = Exclude<
|
||||||
|
T,
|
||||||
|
"raw"
|
||||||
|
> extends never
|
||||||
|
? ApiResult<TData>
|
||||||
|
: ApiResult<TData>["body"]
|
||||||
|
|
||||||
|
export type TConfig<T extends TResult> = {
|
||||||
|
_result?: T
|
||||||
|
}
|
||||||
@@ -1,49 +1,8 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
export { ApiError } from "./core/ApiError"
|
||||||
/* istanbul ignore file */
|
export { CancelablePromise, CancelError } from "./core/CancelablePromise"
|
||||||
/* tslint:disable */
|
export { OpenAPI } from "./core/OpenAPI"
|
||||||
/* eslint-disable */
|
export type { OpenAPIConfig } from "./core/OpenAPI"
|
||||||
export { ApiError } from './core/ApiError';
|
|
||||||
export { CancelablePromise, CancelError } from './core/CancelablePromise';
|
|
||||||
export { OpenAPI } from './core/OpenAPI';
|
|
||||||
export type { OpenAPIConfig } from './core/OpenAPI';
|
|
||||||
|
|
||||||
export type { Body_login_login_access_token } from './models/Body_login_login_access_token';
|
export * from "./models"
|
||||||
export type { HTTPValidationError } from './models/HTTPValidationError';
|
export * from "./schemas"
|
||||||
export type { ItemCreate } from './models/ItemCreate';
|
export * from "./services"
|
||||||
export type { ItemOut } from './models/ItemOut';
|
|
||||||
export type { ItemsOut } from './models/ItemsOut';
|
|
||||||
export type { ItemUpdate } from './models/ItemUpdate';
|
|
||||||
export type { Message } from './models/Message';
|
|
||||||
export type { NewPassword } from './models/NewPassword';
|
|
||||||
export type { Token } from './models/Token';
|
|
||||||
export type { UpdatePassword } from './models/UpdatePassword';
|
|
||||||
export type { UserCreate } from './models/UserCreate';
|
|
||||||
export type { UserCreateOpen } from './models/UserCreateOpen';
|
|
||||||
export type { UserOut } from './models/UserOut';
|
|
||||||
export type { UsersOut } from './models/UsersOut';
|
|
||||||
export type { UserUpdate } from './models/UserUpdate';
|
|
||||||
export type { UserUpdateMe } from './models/UserUpdateMe';
|
|
||||||
export type { ValidationError } from './models/ValidationError';
|
|
||||||
|
|
||||||
export { $Body_login_login_access_token } from './schemas/$Body_login_login_access_token';
|
|
||||||
export { $HTTPValidationError } from './schemas/$HTTPValidationError';
|
|
||||||
export { $ItemCreate } from './schemas/$ItemCreate';
|
|
||||||
export { $ItemOut } from './schemas/$ItemOut';
|
|
||||||
export { $ItemsOut } from './schemas/$ItemsOut';
|
|
||||||
export { $ItemUpdate } from './schemas/$ItemUpdate';
|
|
||||||
export { $Message } from './schemas/$Message';
|
|
||||||
export { $NewPassword } from './schemas/$NewPassword';
|
|
||||||
export { $Token } from './schemas/$Token';
|
|
||||||
export { $UpdatePassword } from './schemas/$UpdatePassword';
|
|
||||||
export { $UserCreate } from './schemas/$UserCreate';
|
|
||||||
export { $UserCreateOpen } from './schemas/$UserCreateOpen';
|
|
||||||
export { $UserOut } from './schemas/$UserOut';
|
|
||||||
export { $UsersOut } from './schemas/$UsersOut';
|
|
||||||
export { $UserUpdate } from './schemas/$UserUpdate';
|
|
||||||
export { $UserUpdateMe } from './schemas/$UserUpdateMe';
|
|
||||||
export { $ValidationError } from './schemas/$ValidationError';
|
|
||||||
|
|
||||||
export { ItemsService } from './services/ItemsService';
|
|
||||||
export { LoginService } from './services/LoginService';
|
|
||||||
export { UsersService } from './services/UsersService';
|
|
||||||
export { UtilsService } from './services/UtilsService';
|
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
export type Body_login_login_access_token = {
|
||||||
|
grant_type?: string | null
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
scope?: string
|
||||||
|
client_id?: string | null
|
||||||
|
client_secret?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HTTPValidationError = {
|
||||||
|
detail?: Array<ValidationError>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ItemCreate = {
|
||||||
|
title: string
|
||||||
|
description?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ItemPublic = {
|
||||||
|
title: string
|
||||||
|
description?: string | null
|
||||||
|
id: string
|
||||||
|
owner_id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ItemUpdate = {
|
||||||
|
title?: string | null
|
||||||
|
description?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ItemsPublic = {
|
||||||
|
data: Array<ItemPublic>
|
||||||
|
count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Message = {
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NewPassword = {
|
||||||
|
token: string
|
||||||
|
new_password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Token = {
|
||||||
|
access_token: string
|
||||||
|
token_type?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UpdatePassword = {
|
||||||
|
current_password: string
|
||||||
|
new_password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserCreate = {
|
||||||
|
email: string
|
||||||
|
is_active?: boolean
|
||||||
|
is_superuser?: boolean
|
||||||
|
full_name?: string | null
|
||||||
|
password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserPublic = {
|
||||||
|
email: string
|
||||||
|
is_active?: boolean
|
||||||
|
is_superuser?: boolean
|
||||||
|
full_name?: string | null
|
||||||
|
id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserRegister = {
|
||||||
|
email: string
|
||||||
|
password: string
|
||||||
|
full_name?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserUpdate = {
|
||||||
|
email?: string | null
|
||||||
|
is_active?: boolean
|
||||||
|
is_superuser?: boolean
|
||||||
|
full_name?: string | null
|
||||||
|
password?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UserUpdateMe = {
|
||||||
|
full_name?: string | null
|
||||||
|
email?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UsersPublic = {
|
||||||
|
data: Array<UserPublic>
|
||||||
|
count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ValidationError = {
|
||||||
|
loc: Array<string | number>
|
||||||
|
msg: string
|
||||||
|
type: string
|
||||||
|
}
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type Body_login_login_access_token = {
|
|
||||||
grant_type?: (string | null);
|
|
||||||
username: string;
|
|
||||||
password: string;
|
|
||||||
scope?: string;
|
|
||||||
client_id?: (string | null);
|
|
||||||
client_secret?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
import type { ValidationError } from './ValidationError';
|
|
||||||
|
|
||||||
export type HTTPValidationError = {
|
|
||||||
detail?: Array<ValidationError>;
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type ItemCreate = {
|
|
||||||
title: string;
|
|
||||||
description?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type ItemOut = {
|
|
||||||
title: string;
|
|
||||||
description?: (string | null);
|
|
||||||
id: number;
|
|
||||||
owner_id: number;
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type ItemUpdate = {
|
|
||||||
title?: (string | null);
|
|
||||||
description?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
import type { ItemOut } from './ItemOut';
|
|
||||||
|
|
||||||
export type ItemsOut = {
|
|
||||||
data: Array<ItemOut>;
|
|
||||||
count: number;
|
|
||||||
};
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type Message = {
|
|
||||||
message: string;
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type NewPassword = {
|
|
||||||
token: string;
|
|
||||||
new_password: string;
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type Token = {
|
|
||||||
access_token: string;
|
|
||||||
token_type?: string;
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UpdatePassword = {
|
|
||||||
current_password: string;
|
|
||||||
new_password: string;
|
|
||||||
};
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UserCreate = {
|
|
||||||
email: string;
|
|
||||||
is_active?: boolean;
|
|
||||||
is_superuser?: boolean;
|
|
||||||
full_name?: (string | null);
|
|
||||||
password: string;
|
|
||||||
};
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UserCreateOpen = {
|
|
||||||
email: string;
|
|
||||||
password: string;
|
|
||||||
full_name?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UserOut = {
|
|
||||||
email: string;
|
|
||||||
is_active?: boolean;
|
|
||||||
is_superuser?: boolean;
|
|
||||||
full_name?: (string | null);
|
|
||||||
id: number;
|
|
||||||
};
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UserUpdate = {
|
|
||||||
email?: (string | null);
|
|
||||||
is_active?: boolean;
|
|
||||||
is_superuser?: boolean;
|
|
||||||
full_name?: (string | null);
|
|
||||||
password?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type UserUpdateMe = {
|
|
||||||
full_name?: (string | null);
|
|
||||||
email?: (string | null);
|
|
||||||
};
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
import type { UserOut } from './UserOut';
|
|
||||||
|
|
||||||
export type UsersOut = {
|
|
||||||
data: Array<UserOut>;
|
|
||||||
count: number;
|
|
||||||
};
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
export type ValidationError = {
|
|
||||||
loc: Array<(string | number)>;
|
|
||||||
msg: string;
|
|
||||||
type: string;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
export const $Body_login_login_access_token = {
|
||||||
|
properties: {
|
||||||
|
grant_type: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
pattern: "password",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
username: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
scope: {
|
||||||
|
type: "string",
|
||||||
|
default: "",
|
||||||
|
},
|
||||||
|
client_id: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
client_secret: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $HTTPValidationError = {
|
||||||
|
properties: {
|
||||||
|
detail: {
|
||||||
|
type: "array",
|
||||||
|
contains: {
|
||||||
|
type: "ValidationError",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $ItemCreate = {
|
||||||
|
properties: {
|
||||||
|
title: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 255,
|
||||||
|
minLength: 1,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $ItemPublic = {
|
||||||
|
properties: {
|
||||||
|
title: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 255,
|
||||||
|
minLength: 1,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
id: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "uuid",
|
||||||
|
},
|
||||||
|
owner_id: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "uuid",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $ItemUpdate = {
|
||||||
|
properties: {
|
||||||
|
title: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
minLength: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $ItemsPublic = {
|
||||||
|
properties: {
|
||||||
|
data: {
|
||||||
|
type: "array",
|
||||||
|
contains: {
|
||||||
|
type: "ItemPublic",
|
||||||
|
},
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
count: {
|
||||||
|
type: "number",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $Message = {
|
||||||
|
properties: {
|
||||||
|
message: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $NewPassword = {
|
||||||
|
properties: {
|
||||||
|
token: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
new_password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $Token = {
|
||||||
|
properties: {
|
||||||
|
access_token: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
token_type: {
|
||||||
|
type: "string",
|
||||||
|
default: "bearer",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UpdatePassword = {
|
||||||
|
properties: {
|
||||||
|
current_password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
new_password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UserCreate = {
|
||||||
|
properties: {
|
||||||
|
email: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "email",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
is_active: {
|
||||||
|
type: "boolean",
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
is_superuser: {
|
||||||
|
type: "boolean",
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
full_name: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UserPublic = {
|
||||||
|
properties: {
|
||||||
|
email: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "email",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
is_active: {
|
||||||
|
type: "boolean",
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
is_superuser: {
|
||||||
|
type: "boolean",
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
full_name: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
id: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "uuid",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UserRegister = {
|
||||||
|
properties: {
|
||||||
|
email: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
format: "email",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
full_name: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UserUpdate = {
|
||||||
|
properties: {
|
||||||
|
email: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
format: "email",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
is_active: {
|
||||||
|
type: "boolean",
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
is_superuser: {
|
||||||
|
type: "boolean",
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
full_name: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 40,
|
||||||
|
minLength: 8,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UserUpdateMe = {
|
||||||
|
properties: {
|
||||||
|
full_name: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
format: "email",
|
||||||
|
maxLength: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "null",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $UsersPublic = {
|
||||||
|
properties: {
|
||||||
|
data: {
|
||||||
|
type: "array",
|
||||||
|
contains: {
|
||||||
|
type: "UserPublic",
|
||||||
|
},
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
count: {
|
||||||
|
type: "number",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export const $ValidationError = {
|
||||||
|
properties: {
|
||||||
|
loc: {
|
||||||
|
type: "array",
|
||||||
|
contains: {
|
||||||
|
type: "any-of",
|
||||||
|
contains: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "number",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
msg: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: "string",
|
||||||
|
isRequired: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $Body_login_login_access_token = {
|
|
||||||
properties: {
|
|
||||||
grant_type: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
pattern: 'password',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
username: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
password: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
scope: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
client_id: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
client_secret: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $HTTPValidationError = {
|
|
||||||
properties: {
|
|
||||||
detail: {
|
|
||||||
type: 'array',
|
|
||||||
contains: {
|
|
||||||
type: 'ValidationError',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $ItemCreate = {
|
|
||||||
properties: {
|
|
||||||
title: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
description: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $ItemOut = {
|
|
||||||
properties: {
|
|
||||||
title: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
description: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
id: {
|
|
||||||
type: 'number',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
owner_id: {
|
|
||||||
type: 'number',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $ItemUpdate = {
|
|
||||||
properties: {
|
|
||||||
title: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
description: {
|
|
||||||
type: 'any-of',
|
|
||||||
contains: [{
|
|
||||||
type: 'string',
|
|
||||||
}, {
|
|
||||||
type: 'null',
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $ItemsOut = {
|
|
||||||
properties: {
|
|
||||||
data: {
|
|
||||||
type: 'array',
|
|
||||||
contains: {
|
|
||||||
type: 'ItemOut',
|
|
||||||
},
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
count: {
|
|
||||||
type: 'number',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $Message = {
|
|
||||||
properties: {
|
|
||||||
message: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $NewPassword = {
|
|
||||||
properties: {
|
|
||||||
token: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
new_password: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $Token = {
|
|
||||||
properties: {
|
|
||||||
access_token: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
token_type: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
/* generated using openapi-typescript-codegen -- do no edit */
|
|
||||||
/* istanbul ignore file */
|
|
||||||
/* tslint:disable */
|
|
||||||
/* eslint-disable */
|
|
||||||
export const $UpdatePassword = {
|
|
||||||
properties: {
|
|
||||||
current_password: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
new_password: {
|
|
||||||
type: 'string',
|
|
||||||
isRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user