Skip to content

Commit

Permalink
Docs: update merge script + added to git unite_api.yaml
Browse files Browse the repository at this point in the history
Docs: update merge script + added to git unite_api.yaml
Login: fix errors responses
  • Loading branch information
sabudilovskiy authored Apr 9, 2023
1 parent b7226dd commit 2b91e4a
Show file tree
Hide file tree
Showing 22 changed files with 943 additions and 94 deletions.
4 changes: 4 additions & 0 deletions .gen/objs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,19 @@ src/utils/convert/base.hpp
src/utils/constexpr_string.hpp
src/utils/component_list_fwd.hpp
src/models/user_type/type.hpp
src/models/user_type/serialize.hpp
src/models/user_type/serialize.cpp
src/models/user_type/postgre.hpp
src/models/user_type/parse.hpp
src/models/user_type/parse.cpp
src/models/user/type.hpp
src/models/user/postgre.hpp
src/models/lesson/type.hpp
src/models/auth_token/type.hpp
src/models/auth_token/serialize.hpp
src/http/legacy_handler_parsed.hpp
src/http/handler_parsed.hpp
src/http/ErrorV1.hpp
src/components/controllers/user_controller_fwd.hpp
src/components/controllers/user_controller_fwd.cpp
src/components/controllers/user_controller.hpp
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ jobs:
- name: Gen list of source and check diffs with commit
run: |
make gen
make unite-api
make check-git-status
- name: Reuse ccache directory
uses: actions/cache@v2
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ gen:

.PHONY: unite-api
unite-api:
@python3 srcipts/merge_yaml.py api/api.yaml merged_api.yaml
@python3 scripts/merge_yaml.py api/api.yaml united_api.yaml

# Internal hidden targets that are used only in docker environment
--in-docker-start-debug --in-docker-start-release: --in-docker-start-%: install-%
Expand Down
7 changes: 1 addition & 6 deletions api/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,4 @@ paths:
/admin/teacher/link:
$ref: views/admin/teacher/link/view.yaml
/admin/teacher/unlink:
$ref: views/admin/teacher/unlink/view.yaml
components:
schemas:
AuthTokenV1:
$ref: types/AuthTokenV1.yaml

$ref: views/admin/teacher/unlink/view.yaml
14 changes: 7 additions & 7 deletions api/types/Day.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
type: integer
type: string
enum:
- 1
- 2
- 3
- 4
- 5
- 6
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
6 changes: 4 additions & 2 deletions api/types/LessonV1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ properties:
$ref: './TypeOfWeek.yaml'
subgroup:
$ref: './Subgroup.yaml'
start:
begin:
$ref: './Timestamp.yaml'
end:
$ref: './Timestamp.yaml'
$ref: './Timestamp.yaml'
type_lesson:
$ref: './TypeOfLesson.yaml'
10 changes: 5 additions & 5 deletions api/types/Subgroup.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
description: 'Тип подгруппы: 0 - для обеих, 1 - только для левой, 2 - только для правой'
type: integer
description: 'Тип подгруппы: All - для обеих'
type: string
enum:
- 0
- 1
- 2
- All
- First
- Second
6 changes: 6 additions & 0 deletions api/types/TypeOfLesson.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
description: 'Тип пары'
type: string
enum:
- Labaratory
- Lection
- Practice
10 changes: 5 additions & 5 deletions api/types/TypeOfWeek.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
description: 'Тип недели: 0 - всегда, 1 - только по числителю, 2 - только по знаменателю'
type: integer
description: 'Тип недели: All - всегда, Even - только по числителю, Odd - только по знаменателю'
type: string
enum:
- 0
- 1
- 2
- All
- Even
- Odd
2 changes: 1 addition & 1 deletion api/types/UserTypeV1.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type: string
enum:
- 'student'
- 'user'
- 'teacher'
- 'admin'
- 'root' #may be unused
4 changes: 3 additions & 1 deletion api/views/login/view.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ post:
application/json:
schema:
$ref : './ResponseV1.yaml'
'404':
'400':
description: Не переданы необходимые параметры
'401':
description: Имя пользователя или пароль не верны
content:
application/json:
Expand Down
2 changes: 1 addition & 1 deletion postgresql/data/initial_data_auth.sql
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
INSERT INTO vsu_timetable.user(login, password, user_type)
VALUES('test_user', 'password123', 'user');
VALUES('some_nickname', 'some_password', 'user');
88 changes: 74 additions & 14 deletions scripts/merge_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,16 @@ def resolve_refs(content, base_path, resolved_files):
resolve_refs(item, base_path, resolved_files)
return content


def is_ref_to_schemas(v):
return v.startswith('#/components/schemas')


def have_refs(yaml):
if isinstance(yaml, dict):
for k, v in yaml.items():
if k == '$ref':
return True
return not is_ref_to_schemas(v)
elif have_refs(v):
return True
elif isinstance(yaml, list):
Expand All @@ -39,42 +44,96 @@ def have_refs(yaml):
return True
return False

def replace_ref(yaml, dir_path, ref_path, ref_src):

def get_ref_name(base_path, path_to_file):
relative_path = os.path.relpath(path_to_file, base_path)
relative_path = relative_path.replace("\\", "/")

if relative_path.startswith("./"):
relative_path = relative_path[2:]

if relative_path.endswith("."):
relative_path = relative_path[:-1]

file_extension = os.path.splitext(relative_path)[-1]
if file_extension:
relative_path = relative_path[:-len(file_extension)]

result = ""
relative_path = relative_path.replace('-', '/')
relative_path = relative_path.replace('_', '/')
for word in relative_path.split('/'):
temp = word[0].upper() + word[1:]
result += temp

return result

def get_ref_name_path(base_path, path_to_file):
result = '#/components/schemas/' + get_ref_name(base_path, path_to_file)
return result

def replace_ref(yaml, dir_path, ref_path, ref_name):
if isinstance(yaml, dict):
for k, v in yaml.items():
if isinstance(v, dict):
if len(v) == 1 and '$ref' in v.keys():
if isinstance(v['$ref'], str):
check_path = os.path.abspath(os.path.join(dir_path, v['$ref']))
if check_path == ref_path:
yaml[k] = ref_src
yaml[k] = {'$ref': ref_name}
else:
replace_ref(v, dir_path, ref_path, ref_src)
replace_ref(v, dir_path, ref_path, ref_name)
elif isinstance(v, list):
for count, item in enumerate(v):
if isinstance(item, dict) and len(item) == 1 and '$ref' in item.keys():
v[count] = ref_src
check_path = os.path.abspath(os.path.join(dir_path, item['$ref']))
if check_path == ref_path:
v[count] = {'$ref': ref_name}
else:
replace_ref(v[count], dir_path, ref_path, ref_src)
replace_ref(v[count], dir_path, ref_path, ref_name)
elif isinstance(yaml, list):
for count, item in enumerate(yaml):
if isinstance(item, dict) and len(item) == 1 and '$ref' in item.keys():
yaml[count] = ref_src
yaml[count] = {'$ref': ref_name}
else:
replace_ref(yaml[count], dir_path, ref_path, ref_src)

replace_ref(yaml[count], dir_path, ref_path, ref_name)


def create_final_content(refs):
def create_final_content(refs, base_path):
components_schemas = {}
while len(refs) > 1:
old_refs = refs.copy()
for replacer_filepath, replacer_data in old_refs.items():
if not have_refs(replacer_data):
ref_name_path = get_ref_name_path(base_path, replacer_filepath)
ref_name = get_ref_name(base_path, replacer_filepath)
for filepath, data in refs.items():
replace_ref(data, os.path.dirname(filepath), replacer_filepath, replacer_data)
replace_ref(data, os.path.dirname(filepath), replacer_filepath, ref_name_path)
if len(refs) > 1:
components_schemas[ref_name] = replacer_data
refs.pop(replacer_filepath)
return list(refs.values())[0]
result = list(refs.values())[0]
result.setdefault('components', {})
result['components'].setdefault('schemas', components_schemas)
return result

def remove_schema_prefix(s):
prefix = "#/components/schemas/"
if s.startswith(prefix):
s = s[len(prefix):]
return s

def fix_views(yaml):
newyaml = yaml
for k, v in yaml['paths'].items():
if isinstance(v, dict):
if len(v) == 1 and '$ref' in v.keys():
name_schema = remove_schema_prefix(v['$ref'])
newyaml['paths'][k] = yaml['components']['schemas'][name_schema]
del newyaml['components']['schemas'][name_schema]
else:
newyaml[k] = v
return newyaml

def main():
if len(sys.argv) < 3:
Expand All @@ -91,9 +150,10 @@ def main():

# Step 3: Create final_content
yaml.Dumper.ignore_aliases = lambda *args: True
final_content = create_final_content(refs)
final_content = create_final_content(refs, os.path.dirname(input_path))
fixed = fix_views(final_content)
with open(output_path, 'w', encoding='utf-8') as result_f:
yaml.dump(final_content, result_f, allow_unicode=True)
yaml.dump(fixed, result_f, allow_unicode=True)


if __name__ == '__main__':
Expand Down
17 changes: 17 additions & 0 deletions src/http/ErrorV1.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#pragma once
#include "../utils/convert/base.hpp"
#include "userver/server/http/http_status.hpp"

namespace timetable_vsu_backend::http {
namespace convert = timetable_vsu_backend::utils::convert;
template <userver::server::http::HttpStatus code>
struct ErrorV1 {
static constexpr convert::TypeOfBody kTypeOfBody =
convert::TypeOfBody::Json;
static constexpr convert::PolicyFields kPolicyFields =
convert::PolicyFields::ConvertAll;
static constexpr userver::server::http::HttpStatus kStatusCode = code;
convert::Property<std::string, "description"> description;
convert::Property<std::string, "machine_id"> machine_id;
};
} // namespace timetable_vsu_backend::http
2 changes: 1 addition & 1 deletion src/http/handler_parsed.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
#include <userver/server/handlers/http_handler_base.hpp>
#include <utility>

#include "../utils/convert/http_response_base.hpp"
#include "userver/formats/json/value.hpp"
#include "userver/formats/json/value_builder.hpp"
#include "userver/server/http/http_status.hpp"
#include "utils/convert/http_response_base.hpp"

namespace timetable_vsu_backend::http {
template <typename Request, typename... TResponse>
Expand Down
15 changes: 15 additions & 0 deletions src/models/lesson/type.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once
#include <boost/uuid/uuid.hpp>

#include "utils/convert/base.hpp"

namespace convert = timetable_vsu_backend::utils::convert;

struct LessonV1 {
convert::Property<boost::uuids::uuid, "room_id"> room_id;
convert::Property<std::string, "room_name"> room_name;
convert::Property<boost::uuids::uuid, "teacher_id"> teacher_id;
convert::Property<std::string, "teacher_fio"> teacher_fio;
convert::Property<boost::uuids::uuid, "subject_id"> subject_id;
convert::Property<std::string, "subject_name"> subject_name;
};
26 changes: 26 additions & 0 deletions src/models/user_type/serialize.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include "serialize.hpp"

#include "userver/formats/json/value_builder.hpp"

namespace timetable_vsu_backend::models {
std::string Serialize(const UserType& value,
userver::formats::serialize::To<std::string>) {
switch (value) {
case UserType::kUser:
return "user";
case UserType::kAdmin:
return "admin";
case UserType::kRoot:
return "root";
case UserType::kTeacher:
return "teacher";
}
}
userver::formats::json::Value Serialize(
const UserType& value,
userver::formats::serialize::To<userver::formats::json::Value>) {
std::string str =
Serialize(value, userver::formats::serialize::To<std::string>{});
return userver::formats::json::ValueBuilder(str).ExtractValue();
}
} // namespace timetable_vsu_backend::models
11 changes: 11 additions & 0 deletions src/models/user_type/serialize.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once
#include "type.hpp"
#include "userver/formats/json/value.hpp"

namespace timetable_vsu_backend::models {
userver::formats::json::Value Serialize(
const UserType& value,
userver::formats::serialize::To<userver::formats::json::Value>);
std::string Serialize(const UserType& value,
userver::formats::serialize::To<std::string>);
} // namespace timetable_vsu_backend::models
Loading

0 comments on commit 2b91e4a

Please sign in to comment.