add open workspace handler

This commit is contained in:
appflowy 2021-08-27 23:53:53 +08:00
parent dd2cec28e4
commit 138998aebd
34 changed files with 476 additions and 474 deletions

View File

@ -43,12 +43,12 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {
SignInState stateFromCode(UserError error) { SignInState stateFromCode(UserError error) {
switch (error.code) { switch (error.code) {
case UserErrCode.EmailInvalid: case UserErrCode.EmailFormatInvalid:
return state.copyWith( return state.copyWith(
isSubmitting: false, isSubmitting: false,
emailError: some(error.msg), emailError: some(error.msg),
passwordError: none()); passwordError: none());
case UserErrCode.PasswordInvalid: case UserErrCode.PasswordFormatInvalid:
return state.copyWith( return state.copyWith(
isSubmitting: false, isSubmitting: false,
passwordError: some(error.msg), passwordError: some(error.msg),

View File

@ -40,6 +40,7 @@ class WorkspaceRepo {
{bool readApps = false}) { {bool readApps = false}) {
final request = QueryWorkspaceRequest.create() final request = QueryWorkspaceRequest.create()
..workspaceId = user.workspace ..workspaceId = user.workspace
..user_id = user.id
..readApps = readApps; ..readApps = readApps;
return WorkspaceEventReadWorkspace(request).send().then((result) { return WorkspaceEventReadWorkspace(request).send().then((result) {

View File

@ -70,12 +70,12 @@ class WorkspaceEventDeleteWorkspace {
class WorkspaceEventReadAllWorkspace { class WorkspaceEventReadAllWorkspace {
WorkspaceEventReadAllWorkspace(); WorkspaceEventReadAllWorkspace();
Future<Either<Workspaces, WorkspaceError>> send() { Future<Either<RepeatedWorkspace, WorkspaceError>> send() {
final request = FFIRequest.create() final request = FFIRequest.create()
..event = WorkspaceEvent.ReadAllWorkspace.toString(); ..event = WorkspaceEvent.ReadAllWorkspace.toString();
return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold( return Dispatch.asyncRequest(request).then((bytesResult) => bytesResult.fold(
(okBytes) => left(Workspaces.fromBuffer(okBytes)), (okBytes) => left(RepeatedWorkspace.fromBuffer(okBytes)),
(errBytes) => right(WorkspaceError.fromBuffer(errBytes)), (errBytes) => right(WorkspaceError.fromBuffer(errBytes)),
)); ));
} }

View File

@ -19,7 +19,6 @@ class UserDetail extends $pb.GeneratedMessage {
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'email') ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'email')
..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name') ..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name')
..e<UserStatus>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'status', $pb.PbFieldType.OE, defaultOrMaker: UserStatus.Unknown, valueOf: UserStatus.valueOf, enumValues: UserStatus.values) ..e<UserStatus>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'status', $pb.PbFieldType.OE, defaultOrMaker: UserStatus.Unknown, valueOf: UserStatus.valueOf, enumValues: UserStatus.values)
..aOS(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspace')
..hasRequiredFields = false ..hasRequiredFields = false
; ;
@ -29,7 +28,6 @@ class UserDetail extends $pb.GeneratedMessage {
$core.String? email, $core.String? email,
$core.String? name, $core.String? name,
UserStatus? status, UserStatus? status,
$core.String? workspace,
}) { }) {
final _result = create(); final _result = create();
if (id != null) { if (id != null) {
@ -44,9 +42,6 @@ class UserDetail extends $pb.GeneratedMessage {
if (status != null) { if (status != null) {
_result.status = status; _result.status = status;
} }
if (workspace != null) {
_result.workspace = workspace;
}
return _result; return _result;
} }
factory UserDetail.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); factory UserDetail.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
@ -105,14 +100,5 @@ class UserDetail extends $pb.GeneratedMessage {
$core.bool hasStatus() => $_has(3); $core.bool hasStatus() => $_has(3);
@$pb.TagNumber(4) @$pb.TagNumber(4)
void clearStatus() => clearField(4); void clearStatus() => clearField(4);
@$pb.TagNumber(5)
$core.String get workspace => $_getSZ(4);
@$pb.TagNumber(5)
set workspace($core.String v) { $_setString(4, v); }
@$pb.TagNumber(5)
$core.bool hasWorkspace() => $_has(4);
@$pb.TagNumber(5)
void clearWorkspace() => clearField(5);
} }

View File

@ -28,9 +28,8 @@ const UserDetail$json = const {
const {'1': 'email', '3': 2, '4': 1, '5': 9, '10': 'email'}, const {'1': 'email', '3': 2, '4': 1, '5': 9, '10': 'email'},
const {'1': 'name', '3': 3, '4': 1, '5': 9, '10': 'name'}, const {'1': 'name', '3': 3, '4': 1, '5': 9, '10': 'name'},
const {'1': 'status', '3': 4, '4': 1, '5': 14, '6': '.UserStatus', '10': 'status'}, const {'1': 'status', '3': 4, '4': 1, '5': 14, '6': '.UserStatus', '10': 'status'},
const {'1': 'workspace', '3': 5, '4': 1, '5': 9, '10': 'workspace'},
], ],
}; };
/// Descriptor for `UserDetail`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `UserDetail`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List userDetailDescriptor = $convert.base64Decode('CgpVc2VyRGV0YWlsEg4KAmlkGAEgASgJUgJpZBIUCgVlbWFpbBgCIAEoCVIFZW1haWwSEgoEbmFtZRgDIAEoCVIEbmFtZRIjCgZzdGF0dXMYBCABKA4yCy5Vc2VyU3RhdHVzUgZzdGF0dXMSHAoJd29ya3NwYWNlGAUgASgJUgl3b3Jrc3BhY2U='); final $typed_data.Uint8List userDetailDescriptor = $convert.base64Decode('CgpVc2VyRGV0YWlsEg4KAmlkGAEgASgJUgJpZBIUCgVlbWFpbBgCIAEoCVIFZW1haWwSEgoEbmFtZRgDIAEoCVIEbmFtZRIjCgZzdGF0dXMYBCABKA4yCy5Vc2VyU3RhdHVzUgZzdGF0dXM=');

View File

@ -9,24 +9,34 @@ import 'dart:core' as $core;
import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/protobuf.dart' as $pb;
enum QueryWorkspaceRequest_OneOfWorkspaceId {
workspaceId,
notSet
}
class QueryWorkspaceRequest extends $pb.GeneratedMessage { class QueryWorkspaceRequest extends $pb.GeneratedMessage {
static const $core.Map<$core.int, QueryWorkspaceRequest_OneOfWorkspaceId> _QueryWorkspaceRequest_OneOfWorkspaceIdByTag = {
1 : QueryWorkspaceRequest_OneOfWorkspaceId.workspaceId,
0 : QueryWorkspaceRequest_OneOfWorkspaceId.notSet
};
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'QueryWorkspaceRequest', createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'QueryWorkspaceRequest', createEmptyInstance: create)
..oo(0, [1])
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId')
..aOB(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'readApps') ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'userId')
..hasRequiredFields = false ..hasRequiredFields = false
; ;
QueryWorkspaceRequest._() : super(); QueryWorkspaceRequest._() : super();
factory QueryWorkspaceRequest({ factory QueryWorkspaceRequest({
$core.String? workspaceId, $core.String? workspaceId,
$core.bool? readApps, $core.String? userId,
}) { }) {
final _result = create(); final _result = create();
if (workspaceId != null) { if (workspaceId != null) {
_result.workspaceId = workspaceId; _result.workspaceId = workspaceId;
} }
if (readApps != null) { if (userId != null) {
_result.readApps = readApps; _result.userId = userId;
} }
return _result; return _result;
} }
@ -51,6 +61,9 @@ class QueryWorkspaceRequest extends $pb.GeneratedMessage {
static QueryWorkspaceRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<QueryWorkspaceRequest>(create); static QueryWorkspaceRequest getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<QueryWorkspaceRequest>(create);
static QueryWorkspaceRequest? _defaultInstance; static QueryWorkspaceRequest? _defaultInstance;
QueryWorkspaceRequest_OneOfWorkspaceId whichOneOfWorkspaceId() => _QueryWorkspaceRequest_OneOfWorkspaceIdByTag[$_whichOneof(0)]!;
void clearOneOfWorkspaceId() => clearField($_whichOneof(0));
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.String get workspaceId => $_getSZ(0); $core.String get workspaceId => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -61,33 +74,43 @@ class QueryWorkspaceRequest extends $pb.GeneratedMessage {
void clearWorkspaceId() => clearField(1); void clearWorkspaceId() => clearField(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool get readApps => $_getBF(1); $core.String get userId => $_getSZ(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set readApps($core.bool v) { $_setBool(1, v); } set userId($core.String v) { $_setString(1, v); }
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasReadApps() => $_has(1); $core.bool hasUserId() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
void clearReadApps() => clearField(2); void clearUserId() => clearField(2);
}
enum QueryWorkspaceParams_OneOfWorkspaceId {
workspaceId,
notSet
} }
class QueryWorkspaceParams extends $pb.GeneratedMessage { class QueryWorkspaceParams extends $pb.GeneratedMessage {
static const $core.Map<$core.int, QueryWorkspaceParams_OneOfWorkspaceId> _QueryWorkspaceParams_OneOfWorkspaceIdByTag = {
1 : QueryWorkspaceParams_OneOfWorkspaceId.workspaceId,
0 : QueryWorkspaceParams_OneOfWorkspaceId.notSet
};
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'QueryWorkspaceParams', createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'QueryWorkspaceParams', createEmptyInstance: create)
..oo(0, [1])
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId')
..aOB(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'readApps') ..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'userId')
..hasRequiredFields = false ..hasRequiredFields = false
; ;
QueryWorkspaceParams._() : super(); QueryWorkspaceParams._() : super();
factory QueryWorkspaceParams({ factory QueryWorkspaceParams({
$core.String? workspaceId, $core.String? workspaceId,
$core.bool? readApps, $core.String? userId,
}) { }) {
final _result = create(); final _result = create();
if (workspaceId != null) { if (workspaceId != null) {
_result.workspaceId = workspaceId; _result.workspaceId = workspaceId;
} }
if (readApps != null) { if (userId != null) {
_result.readApps = readApps; _result.userId = userId;
} }
return _result; return _result;
} }
@ -112,6 +135,9 @@ class QueryWorkspaceParams extends $pb.GeneratedMessage {
static QueryWorkspaceParams getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<QueryWorkspaceParams>(create); static QueryWorkspaceParams getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<QueryWorkspaceParams>(create);
static QueryWorkspaceParams? _defaultInstance; static QueryWorkspaceParams? _defaultInstance;
QueryWorkspaceParams_OneOfWorkspaceId whichOneOfWorkspaceId() => _QueryWorkspaceParams_OneOfWorkspaceIdByTag[$_whichOneof(0)]!;
void clearOneOfWorkspaceId() => clearField($_whichOneof(0));
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.String get workspaceId => $_getSZ(0); $core.String get workspaceId => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -122,12 +148,12 @@ class QueryWorkspaceParams extends $pb.GeneratedMessage {
void clearWorkspaceId() => clearField(1); void clearWorkspaceId() => clearField(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool get readApps => $_getBF(1); $core.String get userId => $_getSZ(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set readApps($core.bool v) { $_setBool(1, v); } set userId($core.String v) { $_setString(1, v); }
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasReadApps() => $_has(1); $core.bool hasUserId() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
void clearReadApps() => clearField(2); void clearUserId() => clearField(2);
} }

View File

@ -12,21 +12,27 @@ import 'dart:typed_data' as $typed_data;
const QueryWorkspaceRequest$json = const { const QueryWorkspaceRequest$json = const {
'1': 'QueryWorkspaceRequest', '1': 'QueryWorkspaceRequest',
'2': const [ '2': const [
const {'1': 'workspace_id', '3': 1, '4': 1, '5': 9, '10': 'workspaceId'}, const {'1': 'workspace_id', '3': 1, '4': 1, '5': 9, '9': 0, '10': 'workspaceId'},
const {'1': 'read_apps', '3': 2, '4': 1, '5': 8, '10': 'readApps'}, const {'1': 'user_id', '3': 2, '4': 1, '5': 9, '10': 'userId'},
],
'8': const [
const {'1': 'one_of_workspace_id'},
], ],
}; };
/// Descriptor for `QueryWorkspaceRequest`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `QueryWorkspaceRequest`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List queryWorkspaceRequestDescriptor = $convert.base64Decode('ChVRdWVyeVdvcmtzcGFjZVJlcXVlc3QSIQoMd29ya3NwYWNlX2lkGAEgASgJUgt3b3Jrc3BhY2VJZBIbCglyZWFkX2FwcHMYAiABKAhSCHJlYWRBcHBz'); final $typed_data.Uint8List queryWorkspaceRequestDescriptor = $convert.base64Decode('ChVRdWVyeVdvcmtzcGFjZVJlcXVlc3QSIwoMd29ya3NwYWNlX2lkGAEgASgJSABSC3dvcmtzcGFjZUlkEhcKB3VzZXJfaWQYAiABKAlSBnVzZXJJZEIVChNvbmVfb2Zfd29ya3NwYWNlX2lk');
@$core.Deprecated('Use queryWorkspaceParamsDescriptor instead') @$core.Deprecated('Use queryWorkspaceParamsDescriptor instead')
const QueryWorkspaceParams$json = const { const QueryWorkspaceParams$json = const {
'1': 'QueryWorkspaceParams', '1': 'QueryWorkspaceParams',
'2': const [ '2': const [
const {'1': 'workspace_id', '3': 1, '4': 1, '5': 9, '10': 'workspaceId'}, const {'1': 'workspace_id', '3': 1, '4': 1, '5': 9, '9': 0, '10': 'workspaceId'},
const {'1': 'read_apps', '3': 2, '4': 1, '5': 8, '10': 'readApps'}, const {'1': 'user_id', '3': 2, '4': 1, '5': 9, '10': 'userId'},
],
'8': const [
const {'1': 'one_of_workspace_id'},
], ],
}; };
/// Descriptor for `QueryWorkspaceParams`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `QueryWorkspaceParams`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List queryWorkspaceParamsDescriptor = $convert.base64Decode('ChRRdWVyeVdvcmtzcGFjZVBhcmFtcxIhCgx3b3Jrc3BhY2VfaWQYASABKAlSC3dvcmtzcGFjZUlkEhsKCXJlYWRfYXBwcxgCIAEoCFIIcmVhZEFwcHM='); final $typed_data.Uint8List queryWorkspaceParamsDescriptor = $convert.base64Decode('ChRRdWVyeVdvcmtzcGFjZVBhcmFtcxIjCgx3b3Jrc3BhY2VfaWQYASABKAlIAFILd29ya3NwYWNlSWQSFwoHdXNlcl9pZBgCIAEoCVIGdXNlcklkQhUKE29uZV9vZl93b3Jrc3BhY2VfaWQ=');

View File

@ -11,20 +11,15 @@ import 'package:protobuf/protobuf.dart' as $pb;
class CurrentWorkspace extends $pb.GeneratedMessage { class CurrentWorkspace extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'CurrentWorkspace', createEmptyInstance: create) static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'CurrentWorkspace', createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'owner') ..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId')
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workspaceId')
..hasRequiredFields = false ..hasRequiredFields = false
; ;
CurrentWorkspace._() : super(); CurrentWorkspace._() : super();
factory CurrentWorkspace({ factory CurrentWorkspace({
$core.String? owner,
$core.String? workspaceId, $core.String? workspaceId,
}) { }) {
final _result = create(); final _result = create();
if (owner != null) {
_result.owner = owner;
}
if (workspaceId != null) { if (workspaceId != null) {
_result.workspaceId = workspaceId; _result.workspaceId = workspaceId;
} }
@ -52,21 +47,12 @@ class CurrentWorkspace extends $pb.GeneratedMessage {
static CurrentWorkspace? _defaultInstance; static CurrentWorkspace? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.String get owner => $_getSZ(0); $core.String get workspaceId => $_getSZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set owner($core.String v) { $_setString(0, v); } set workspaceId($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasOwner() => $_has(0); $core.bool hasWorkspaceId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
void clearOwner() => clearField(1); void clearWorkspaceId() => clearField(1);
@$pb.TagNumber(2)
$core.String get workspaceId => $_getSZ(1);
@$pb.TagNumber(2)
set workspaceId($core.String v) { $_setString(1, v); }
@$pb.TagNumber(2)
$core.bool hasWorkspaceId() => $_has(1);
@$pb.TagNumber(2)
void clearWorkspaceId() => clearField(2);
} }

View File

@ -12,10 +12,9 @@ import 'dart:typed_data' as $typed_data;
const CurrentWorkspace$json = const { const CurrentWorkspace$json = const {
'1': 'CurrentWorkspace', '1': 'CurrentWorkspace',
'2': const [ '2': const [
const {'1': 'owner', '3': 1, '4': 1, '5': 9, '10': 'owner'}, const {'1': 'workspace_id', '3': 1, '4': 1, '5': 9, '10': 'workspaceId'},
const {'1': 'workspace_id', '3': 2, '4': 1, '5': 9, '10': 'workspaceId'},
], ],
}; };
/// Descriptor for `CurrentWorkspace`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `CurrentWorkspace`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List currentWorkspaceDescriptor = $convert.base64Decode('ChBDdXJyZW50V29ya3NwYWNlEhQKBW93bmVyGAEgASgJUgVvd25lchIhCgx3b3Jrc3BhY2VfaWQYAiABKAlSC3dvcmtzcGFjZUlk'); final $typed_data.Uint8List currentWorkspaceDescriptor = $convert.base64Decode('ChBDdXJyZW50V29ya3NwYWNlEiEKDHdvcmtzcGFjZV9pZBgBIAEoCVILd29ya3NwYWNlSWQ=');

View File

@ -65,6 +65,8 @@ pub fn run(listener: TcpListener, app_ctx: AppContext) -> Result<Server, std::io
fn ws_scope() -> Scope { web::scope("/ws").service(ws_service::router::start_connection) } fn ws_scope() -> Scope { web::scope("/ws").service(ws_service::router::start_connection) }
fn user_scope() -> Scope { fn user_scope() -> Scope {
// https://developer.mozilla.org/en-US/docs/Web/HTTP
// TODO: replace GET body with query params
web::scope("/api") web::scope("/api")
// authentication // authentication
.service(web::resource("/auth") .service(web::resource("/auth")

View File

@ -14,13 +14,10 @@ use flowy_net::errors::invalid_params;
use flowy_user::entities::parser::UserId; use flowy_user::entities::parser::UserId;
use flowy_workspace::{ use flowy_workspace::{
entities::{ entities::{
app::{ app::parser::{AppDesc, AppId, AppName},
parser::{AppDesc, AppId, AppName},
RepeatedApp,
},
workspace::parser::WorkspaceId, workspace::parser::WorkspaceId,
}, },
protobuf::{App, CreateAppParams, QueryAppParams, RepeatedView, UpdateAppParams}, protobuf::{App, CreateAppParams, QueryAppParams, RepeatedApp, RepeatedView, UpdateAppParams},
}; };
use protobuf::Message; use protobuf::Message;
use sqlx::{postgres::PgArguments, PgPool, Postgres, Transaction}; use sqlx::{postgres::PgArguments, PgPool, Postgres, Transaction};
@ -193,7 +190,7 @@ pub(crate) async fn delete_app(pool: &PgPool, app_id: &str) -> Result<FlowyRespo
pub(crate) async fn read_apps_belong_to_workspace<'c>( pub(crate) async fn read_apps_belong_to_workspace<'c>(
transaction: &mut DBTransaction<'_>, transaction: &mut DBTransaction<'_>,
workspace_id: &str, workspace_id: &str,
) -> Result<Vec<App>, ServerError> { ) -> Result<RepeatedApp, ServerError> {
let workspace_id = WorkspaceId::parse(workspace_id.to_owned()).map_err(invalid_params)?; let workspace_id = WorkspaceId::parse(workspace_id.to_owned()).map_err(invalid_params)?;
let (sql, args) = SqlBuilder::select("app_table") let (sql, args) = SqlBuilder::select("app_table")
.add_field("*") .add_field("*")
@ -210,5 +207,7 @@ pub(crate) async fn read_apps_belong_to_workspace<'c>(
.map(|table| make_app_from_table(table, RepeatedView::default())) .map(|table| make_app_from_table(table, RepeatedView::default()))
.collect::<Vec<App>>(); .collect::<Vec<App>>();
Ok(apps) let mut repeated_app = RepeatedApp::default();
repeated_app.set_items(apps.into());
Ok(repeated_app)
} }

View File

@ -3,8 +3,7 @@ use crate::{
workspace_service::workspace::{ workspace_service::workspace::{
create_workspace, create_workspace,
delete_workspace, delete_workspace,
read_workspace, read_workspaces,
read_workspace_list,
update_workspace, update_workspace,
}, },
}; };
@ -36,7 +35,13 @@ pub async fn read_handler(
pool: Data<PgPool>, pool: Data<PgPool>,
) -> Result<HttpResponse, ServerError> { ) -> Result<HttpResponse, ServerError> {
let params: QueryWorkspaceParams = parse_from_payload(payload).await?; let params: QueryWorkspaceParams = parse_from_payload(payload).await?;
let resp = read_workspace(pool.get_ref(), params).await?; let workspace_id = if params.has_workspace_id() {
Some(params.get_workspace_id().to_owned())
} else {
None
};
let resp = read_workspaces(pool.get_ref(), params.get_user_id(), workspace_id).await?;
Ok(resp.into()) Ok(resp.into())
} }
@ -62,6 +67,6 @@ pub async fn workspace_list(
user_id: Path<String>, user_id: Path<String>,
pool: Data<PgPool>, pool: Data<PgPool>,
) -> Result<HttpResponse, ServerError> { ) -> Result<HttpResponse, ServerError> {
let resp = read_workspace_list(pool.get_ref(), &user_id).await?; let resp = read_workspaces(pool.get_ref(), &user_id, None).await?;
Ok(resp.into()) Ok(resp.into())
} }

View File

@ -59,44 +59,6 @@ pub(crate) async fn create_workspace(
FlowyResponse::success().pb(workspace) FlowyResponse::success().pb(workspace)
} }
pub(crate) async fn read_workspace(
pool: &PgPool,
params: QueryWorkspaceParams,
) -> Result<FlowyResponse, ServerError> {
let workspace_id = check_workspace_id(params.get_workspace_id().to_owned())?;
let mut transaction = pool
.begin()
.await
.context("Failed to acquire a Postgres connection to read workspace")?;
let (sql, args) = SqlBuilder::select("workspace_table")
.add_field("*")
.and_where_eq("id", workspace_id)
.build()?;
let table = sqlx::query_as_with::<Postgres, WorkspaceTable, PgArguments>(&sql, args)
.fetch_one(&mut transaction)
.await
.map_err(map_sqlx_error)?;
let mut repeated_app = RepeatedApp::default();
if params.read_apps {
repeated_app.set_items(
read_apps_belong_to_workspace(&mut transaction, &table.id.to_string())
.await?
.into(),
);
}
transaction
.commit()
.await
.context("Failed to commit SQL transaction to read workspace.")?;
let workspace = make_workspace_from_table(table, Some(repeated_app));
FlowyResponse::success().pb(workspace)
}
pub(crate) async fn update_workspace( pub(crate) async fn update_workspace(
pool: &PgPool, pool: &PgPool,
params: UpdateWorkspaceParams, params: UpdateWorkspaceParams,
@ -173,38 +135,48 @@ pub(crate) async fn delete_workspace(
Ok(FlowyResponse::success()) Ok(FlowyResponse::success())
} }
pub async fn read_workspace_list( pub async fn read_workspaces(
pool: &PgPool, pool: &PgPool,
user_id: &str, user_id: &str,
workspace_id: Option<String>,
) -> Result<FlowyResponse, ServerError> { ) -> Result<FlowyResponse, ServerError> {
let user_id = UserId::parse(user_id.to_string()).map_err(invalid_params)?;
let mut transaction = pool let mut transaction = pool
.begin() .begin()
.await .await
.context("Failed to acquire a Postgres connection to delete workspace")?; .context("Failed to acquire a Postgres connection to read workspace")?;
let (sql, args) = SqlBuilder::select("workspace_table") let mut builder = SqlBuilder::select("workspace_table")
.add_field("*") .add_field("*")
.and_where_eq("user_id", user_id) .and_where_eq("user_id", user_id.as_ref());
.build()?;
if let Some(workspace_id) = workspace_id {
let workspace_id = check_workspace_id(workspace_id)?;
builder = builder.and_where_eq("id", workspace_id);
}
let (sql, args) = builder.build()?;
let tables = sqlx::query_as_with::<Postgres, WorkspaceTable, PgArguments>(&sql, args) let tables = sqlx::query_as_with::<Postgres, WorkspaceTable, PgArguments>(&sql, args)
.fetch_all(&mut transaction) .fetch_all(&mut transaction)
.await .await
.map_err(map_sqlx_error)?; .map_err(map_sqlx_error)?;
let mut repeated_workspace = RepeatedWorkspace::default();
let mut workspaces = vec![];
for table in tables {
let apps = read_apps_belong_to_workspace(&mut transaction, &table.id.to_string())
.await
.context("Get workspace app")
.unwrap_or(RepeatedApp::default());
let workspace = make_workspace_from_table(table, Some(apps));
workspaces.push(workspace);
}
transaction transaction
.commit() .commit()
.await .await
.context("Failed to commit SQL transaction to delete workspace.")?; .context("Failed to commit SQL transaction to read workspace.")?;
let mut workspace = RepeatedWorkspace::default(); repeated_workspace.set_items(workspaces.into());
workspace.set_items(
tables
.into_iter()
.map(|table| make_workspace_from_table(table, None))
.collect::<Vec<Workspace>>()
.into(),
);
FlowyResponse::success().pb(workspace) FlowyResponse::success().pb(repeated_workspace)
} }

View File

@ -33,10 +33,10 @@ impl TestApp {
workspace workspace
} }
pub async fn read_workspace(&self, params: QueryWorkspaceParams) -> Option<Workspace> { pub async fn read_workspace(&self, params: QueryWorkspaceParams) -> RepeatedWorkspace {
let url = format!("{}/api/workspace", self.address); let url = format!("{}/api/workspace", self.address);
let workspace = read_workspace_request(params, &url).await.unwrap(); let workspaces = read_workspaces_request(params, &url).await.unwrap();
workspace workspaces
} }
pub async fn update_workspace(&self, params: UpdateWorkspaceParams) { pub async fn update_workspace(&self, params: UpdateWorkspaceParams) {

View File

@ -21,9 +21,9 @@ async fn workspace_create() {
#[actix_rt::test] #[actix_rt::test]
async fn workspace_read() { async fn workspace_read() {
let app = spawn_app().await; let app = spawn_app().await;
let (workspace_1, _) = create_test_workspace(&app).await; let (workspace_1, user_id) = create_test_workspace(&app).await;
let read_params = QueryWorkspaceParams::new(&workspace_1.id); let read_params = QueryWorkspaceParams::new(&user_id).workspace_id(&workspace_1.id);
log::info!("{:?}", app.read_workspace(read_params).await.unwrap()); log::info!("{:?}", app.read_workspace(read_params).await);
} }
#[actix_rt::test] #[actix_rt::test]
@ -34,15 +34,18 @@ async fn workspace_read_with_belongs() {
let _ = create_test_app(&application, &workspace.id, &user_id).await; let _ = create_test_app(&application, &workspace.id, &user_id).await;
let _ = create_test_app(&application, &workspace.id, &user_id).await; let _ = create_test_app(&application, &workspace.id, &user_id).await;
let read_params = QueryWorkspaceParams::new(&workspace.id).read_apps(); let read_params = QueryWorkspaceParams::new(&user_id)
let workspace = application.read_workspace(read_params).await.unwrap(); .workspace_id(&workspace.id)
.read_apps();
let workspaces = application.read_workspace(read_params).await;
let workspace = workspaces.items.first().unwrap();
assert_eq!(workspace.apps.len(), 3); assert_eq!(workspace.apps.len(), 3);
} }
#[actix_rt::test] #[actix_rt::test]
async fn workspace_update() { async fn workspace_update() {
let app = spawn_app().await; let app = spawn_app().await;
let (workspace_1, _) = create_test_workspace(&app).await; let (workspace_1, user_id) = create_test_workspace(&app).await;
let update_params = UpdateWorkspaceParams { let update_params = UpdateWorkspaceParams {
id: workspace_1.id.clone(), id: workspace_1.id.clone(),
name: Some("workspace 2".to_string()), name: Some("workspace 2".to_string()),
@ -50,28 +53,23 @@ async fn workspace_update() {
}; };
app.update_workspace(update_params).await; app.update_workspace(update_params).await;
let read_params = QueryWorkspaceParams { let read_params = QueryWorkspaceParams::new(&user_id).workspace_id(&workspace_1.id);
workspace_id: workspace_1.id.clone(), let workspace_2 = app.read_workspace(read_params).await;
read_apps: false,
};
let workspace_2 = app.read_workspace(read_params).await.unwrap();
log::info!("{:?}", workspace_2); log::info!("{:?}", workspace_2);
} }
#[actix_rt::test] #[actix_rt::test]
async fn workspace_delete() { async fn workspace_delete() {
let app = spawn_app().await; let app = spawn_app().await;
let (workspace, _) = create_test_workspace(&app).await; let (workspace, user_id) = create_test_workspace(&app).await;
let delete_params = DeleteWorkspaceParams { let delete_params = DeleteWorkspaceParams {
workspace_id: workspace.id.clone(), workspace_id: workspace.id.clone(),
}; };
let _ = app.delete_workspace(delete_params).await; let _ = app.delete_workspace(delete_params).await;
let read_params = QueryWorkspaceParams { let read_params = QueryWorkspaceParams::new(&user_id).workspace_id(&workspace.id);
workspace_id: workspace.id.clone(), let repeated_workspace = app.read_workspace(read_params).await;
read_apps: false, assert_eq!(repeated_workspace.len(), 0);
};
assert_eq!(app.read_workspace(read_params).await.is_none(), true);
} }
async fn create_test_workspace(app: &TestApp) -> (Workspace, String) { async fn create_test_workspace(app: &TestApp) -> (Workspace, String) {
@ -248,8 +246,7 @@ async fn workspace_list_read() {
let _ = application.create_workspace(params).await; let _ = application.create_workspace(params).await;
} }
let workspaces = application.read_workspace_list(&response.uid).await; let read_params = QueryWorkspaceParams::new(&response.uid);
// 3 + 1 (created by default) let workspaces = application.read_workspace(read_params).await;
assert_eq!(workspaces.len(), 4); assert_eq!(workspaces.len(), 4);
log::info!("{:?}", workspaces);
} }

View File

@ -2,7 +2,8 @@ use flowy_dispatch::prelude::*;
use std::sync::Once; use std::sync::Once;
#[allow(dead_code)] #[allow(dead_code)]
= Once::new(); pub fn setup_env() {
static INIT: Once = Once::new();
INIT.call_once(|| { INIT.call_once(|| {
std::env::set_var("RUST_LOG", "flowy_dispatch=debug,debug"); std::env::set_var("RUST_LOG", "flowy_dispatch=debug,debug");
env_logger::init(); env_logger::init();

View File

@ -53,8 +53,7 @@ impl WorkspaceUser for WorkspaceUserImpl {
})?; })?;
Ok(CurrentWorkspace { Ok(CurrentWorkspace {
owner: user_detail.email, workspace_id: "".to_owned(),
workspace_id: user_detail.workspace,
}) })
}), }),
} }

View File

@ -24,9 +24,6 @@ pub struct UserDetail {
#[pb(index = 4)] #[pb(index = 4)]
pub status: UserStatus, pub status: UserStatus,
#[pb(index = 5)]
pub workspace: String,
} }
use crate::sql_tables::UserTable; use crate::sql_tables::UserTable;
@ -37,7 +34,6 @@ impl std::convert::From<UserTable> for UserDetail {
email: user.email, email: user.email,
name: user.name, name: user.name,
status: UserStatus::Login, status: UserStatus::Login,
workspace: user.workspace,
} }
} }
} }

View File

@ -17,9 +17,6 @@ pub struct UpdateUserRequest {
pub email: Option<String>, pub email: Option<String>,
#[pb(index = 4, one_of)] #[pb(index = 4, one_of)]
pub workspace: Option<String>,
#[pb(index = 5, one_of)]
pub password: Option<String>, pub password: Option<String>,
} }
@ -41,11 +38,6 @@ impl UpdateUserRequest {
self self
} }
pub fn workspace(mut self, workspace: &str) -> Self {
self.workspace = Some(workspace.to_owned());
self
}
pub fn password(mut self, password: &str) -> Self { pub fn password(mut self, password: &str) -> Self {
self.password = Some(password.to_owned()); self.password = Some(password.to_owned());
self self
@ -64,9 +56,6 @@ pub struct UpdateUserParams {
pub email: Option<String>, pub email: Option<String>,
#[pb(index = 4, one_of)] #[pb(index = 4, one_of)]
pub workspace: Option<String>,
#[pb(index = 5, one_of)]
pub password: Option<String>, pub password: Option<String>,
} }
@ -96,19 +85,6 @@ impl TryInto<UpdateUserParams> for UpdateUserRequest {
), ),
}; };
let workspace = match self.workspace {
None => None,
Some(workspace) => Some(
UserWorkspace::parse(workspace)
.map_err(|e| {
ErrorBuilder::new(UserErrCode::UserWorkspaceInvalid)
.msg(e)
.build()
})?
.0,
),
};
let password = match self.password { let password = match self.password {
None => None, None => None,
Some(password) => Some( Some(password) => Some(
@ -122,7 +98,6 @@ impl TryInto<UpdateUserParams> for UpdateUserRequest {
id, id,
name, name,
email, email,
workspace,
password, password,
}) })
} }

View File

@ -30,7 +30,6 @@ pub struct UserDetail {
pub email: ::std::string::String, pub email: ::std::string::String,
pub name: ::std::string::String, pub name: ::std::string::String,
pub status: UserStatus, pub status: UserStatus,
pub workspace: ::std::string::String,
// special fields // special fields
pub unknown_fields: ::protobuf::UnknownFields, pub unknown_fields: ::protobuf::UnknownFields,
pub cached_size: ::protobuf::CachedSize, pub cached_size: ::protobuf::CachedSize,
@ -139,32 +138,6 @@ impl UserDetail {
pub fn set_status(&mut self, v: UserStatus) { pub fn set_status(&mut self, v: UserStatus) {
self.status = v; self.status = v;
} }
// string workspace = 5;
pub fn get_workspace(&self) -> &str {
&self.workspace
}
pub fn clear_workspace(&mut self) {
self.workspace.clear();
}
// Param is passed by value, moved
pub fn set_workspace(&mut self, v: ::std::string::String) {
self.workspace = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_workspace(&mut self) -> &mut ::std::string::String {
&mut self.workspace
}
// Take field
pub fn take_workspace(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.workspace, ::std::string::String::new())
}
} }
impl ::protobuf::Message for UserDetail { impl ::protobuf::Message for UserDetail {
@ -188,9 +161,6 @@ impl ::protobuf::Message for UserDetail {
4 => { 4 => {
::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.status, 4, &mut self.unknown_fields)? ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.status, 4, &mut self.unknown_fields)?
}, },
5 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace)?;
},
_ => { _ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
}, },
@ -215,9 +185,6 @@ impl ::protobuf::Message for UserDetail {
if self.status != UserStatus::Unknown { if self.status != UserStatus::Unknown {
my_size += ::protobuf::rt::enum_size(4, self.status); my_size += ::protobuf::rt::enum_size(4, self.status);
} }
if !self.workspace.is_empty() {
my_size += ::protobuf::rt::string_size(5, &self.workspace);
}
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size); self.cached_size.set(my_size);
my_size my_size
@ -236,9 +203,6 @@ impl ::protobuf::Message for UserDetail {
if self.status != UserStatus::Unknown { if self.status != UserStatus::Unknown {
os.write_enum(4, ::protobuf::ProtobufEnum::value(&self.status))?; os.write_enum(4, ::protobuf::ProtobufEnum::value(&self.status))?;
} }
if !self.workspace.is_empty() {
os.write_string(5, &self.workspace)?;
}
os.write_unknown_fields(self.get_unknown_fields())?; os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(()) ::std::result::Result::Ok(())
} }
@ -297,11 +261,6 @@ impl ::protobuf::Message for UserDetail {
|m: &UserDetail| { &m.status }, |m: &UserDetail| { &m.status },
|m: &mut UserDetail| { &mut m.status }, |m: &mut UserDetail| { &mut m.status },
)); ));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"workspace",
|m: &UserDetail| { &m.workspace },
|m: &mut UserDetail| { &mut m.workspace },
));
::protobuf::reflect::MessageDescriptor::new_pb_name::<UserDetail>( ::protobuf::reflect::MessageDescriptor::new_pb_name::<UserDetail>(
"UserDetail", "UserDetail",
fields, fields,
@ -322,7 +281,6 @@ impl ::protobuf::Clear for UserDetail {
self.email.clear(); self.email.clear();
self.name.clear(); self.name.clear();
self.status = UserStatus::Unknown; self.status = UserStatus::Unknown;
self.workspace.clear();
self.unknown_fields.clear(); self.unknown_fields.clear();
} }
} }
@ -393,35 +351,31 @@ impl ::protobuf::reflect::ProtobufValue for UserStatus {
} }
static file_descriptor_proto_data: &'static [u8] = b"\ static file_descriptor_proto_data: &'static [u8] = b"\
\n\x11user_detail.proto\"\x89\x01\n\nUserDetail\x12\x0e\n\x02id\x18\x01\ \n\x11user_detail.proto\"k\n\nUserDetail\x12\x0e\n\x02id\x18\x01\x20\x01\
\x20\x01(\tR\x02id\x12\x14\n\x05email\x18\x02\x20\x01(\tR\x05email\x12\ (\tR\x02id\x12\x14\n\x05email\x18\x02\x20\x01(\tR\x05email\x12\x12\n\x04\
\x12\n\x04name\x18\x03\x20\x01(\tR\x04name\x12#\n\x06status\x18\x04\x20\ name\x18\x03\x20\x01(\tR\x04name\x12#\n\x06status\x18\x04\x20\x01(\x0e2\
\x01(\x0e2\x0b.UserStatusR\x06status\x12\x1c\n\tworkspace\x18\x05\x20\ \x0b.UserStatusR\x06status*1\n\nUserStatus\x12\x0b\n\x07Unknown\x10\0\
\x01(\tR\tworkspace*1\n\nUserStatus\x12\x0b\n\x07Unknown\x10\0\x12\t\n\ \x12\t\n\x05Login\x10\x01\x12\x0b\n\x07Expired\x10\x02J\x99\x03\n\x06\
\x05Login\x10\x01\x12\x0b\n\x07Expired\x10\x02J\xd0\x03\n\x06\x12\x04\0\ \x12\x04\0\0\x0c\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\
\0\r\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\ \x04\x02\0\x07\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x12\n\x0b\n\x04\
\x08\x01\n\n\n\x03\x04\0\x01\x12\x03\x02\x08\x12\n\x0b\n\x04\x04\0\x02\0\ \x04\0\x02\0\x12\x03\x03\x04\x12\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\
\x12\x03\x03\x04\x12\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\ \x04\n\n\x0c\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0b\r\n\x0c\n\x05\x04\0\
\n\x05\x04\0\x02\0\x01\x12\x03\x03\x0b\r\n\x0c\n\x05\x04\0\x02\0\x03\x12\ \x02\0\x03\x12\x03\x03\x10\x11\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\
\x03\x03\x10\x11\n\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x15\n\x0c\n\ \x15\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\
\x05\x04\0\x02\x01\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\ \x02\x01\x01\x12\x03\x04\x0b\x10\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\
\x12\x03\x04\x0b\x10\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x13\x14\n\ \x04\x13\x14\n\x0b\n\x04\x04\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\
\x0b\n\x04\x04\0\x02\x02\x12\x03\x05\x04\x14\n\x0c\n\x05\x04\0\x02\x02\ \x04\0\x02\x02\x05\x12\x03\x05\x04\n\n\x0c\n\x05\x04\0\x02\x02\x01\x12\
\x05\x12\x03\x05\x04\n\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x03\x05\x0b\x0f\ \x03\x05\x0b\x0f\n\x0c\n\x05\x04\0\x02\x02\x03\x12\x03\x05\x12\x13\n\x0b\
\n\x0c\n\x05\x04\0\x02\x02\x03\x12\x03\x05\x12\x13\n\x0b\n\x04\x04\0\x02\ \n\x04\x04\0\x02\x03\x12\x03\x06\x04\x1a\n\x0c\n\x05\x04\0\x02\x03\x06\
\x03\x12\x03\x06\x04\x1a\n\x0c\n\x05\x04\0\x02\x03\x06\x12\x03\x06\x04\ \x12\x03\x06\x04\x0e\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x06\x0f\x15\n\
\x0e\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x03\x06\x0f\x15\n\x0c\n\x05\x04\0\ \x0c\n\x05\x04\0\x02\x03\x03\x12\x03\x06\x18\x19\n\n\n\x02\x05\0\x12\x04\
\x02\x03\x03\x12\x03\x06\x18\x19\n\x0b\n\x04\x04\0\x02\x04\x12\x03\x07\ \x08\0\x0c\x01\n\n\n\x03\x05\0\x01\x12\x03\x08\x05\x0f\n\x0b\n\x04\x05\0\
\x04\x19\n\x0c\n\x05\x04\0\x02\x04\x05\x12\x03\x07\x04\n\n\x0c\n\x05\x04\ \x02\0\x12\x03\t\x04\x10\n\x0c\n\x05\x05\0\x02\0\x01\x12\x03\t\x04\x0b\n\
\0\x02\x04\x01\x12\x03\x07\x0b\x14\n\x0c\n\x05\x04\0\x02\x04\x03\x12\x03\ \x0c\n\x05\x05\0\x02\0\x02\x12\x03\t\x0e\x0f\n\x0b\n\x04\x05\0\x02\x01\
\x07\x17\x18\n\n\n\x02\x05\0\x12\x04\t\0\r\x01\n\n\n\x03\x05\0\x01\x12\ \x12\x03\n\x04\x0e\n\x0c\n\x05\x05\0\x02\x01\x01\x12\x03\n\x04\t\n\x0c\n\
\x03\t\x05\x0f\n\x0b\n\x04\x05\0\x02\0\x12\x03\n\x04\x10\n\x0c\n\x05\x05\ \x05\x05\0\x02\x01\x02\x12\x03\n\x0c\r\n\x0b\n\x04\x05\0\x02\x02\x12\x03\
\0\x02\0\x01\x12\x03\n\x04\x0b\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03\n\x0e\ \x0b\x04\x10\n\x0c\n\x05\x05\0\x02\x02\x01\x12\x03\x0b\x04\x0b\n\x0c\n\
\x0f\n\x0b\n\x04\x05\0\x02\x01\x12\x03\x0b\x04\x0e\n\x0c\n\x05\x05\0\x02\ \x05\x05\0\x02\x02\x02\x12\x03\x0b\x0e\x0fb\x06proto3\
\x01\x01\x12\x03\x0b\x04\t\n\x0c\n\x05\x05\0\x02\x01\x02\x12\x03\x0b\x0c\
\r\n\x0b\n\x04\x05\0\x02\x02\x12\x03\x0c\x04\x10\n\x0c\n\x05\x05\0\x02\
\x02\x01\x12\x03\x0c\x04\x0b\n\x0c\n\x05\x05\0\x02\x02\x02\x12\x03\x0c\
\x0e\x0fb\x06proto3\
"; ";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT;

View File

@ -5,7 +5,6 @@ message UserDetail {
string email = 2; string email = 2;
string name = 3; string name = 3;
UserStatus status = 4; UserStatus status = 4;
string workspace = 5;
} }
enum UserStatus { enum UserStatus {
Unknown = 0; Unknown = 0;

View File

@ -92,13 +92,7 @@ impl UserSession {
Ok(()) Ok(())
} }
async fn save_user(&self, mut user: UserTable) -> Result<UserTable, UserError> { async fn save_user(&self, user: UserTable) -> Result<UserTable, UserError> {
if user.workspace.is_empty() {
log::info!("Try to create user default workspace");
let workspace_id = self.create_default_workspace_if_need(&user.id).await?;
user.workspace = workspace_id;
}
let conn = self.get_db_connection()?; let conn = self.get_db_connection()?;
let _ = diesel::insert_into(user_table::table) let _ = diesel::insert_into(user_table::table)
.values(user.clone()) .values(user.clone())

View File

@ -8,7 +8,7 @@ pub struct UserTable {
pub(crate) name: String, pub(crate) name: String,
pub(crate) password: String, pub(crate) password: String,
pub(crate) email: String, pub(crate) email: String,
pub(crate) workspace: String, pub(crate) workspace: String, // deprecated
} }
impl UserTable { impl UserTable {
@ -44,7 +44,7 @@ impl std::convert::From<SignInResponse> for UserTable {
#[table_name = "user_table"] #[table_name = "user_table"]
pub struct UserTableChangeset { pub struct UserTableChangeset {
pub id: String, pub id: String,
pub workspace: Option<String>, pub workspace: Option<String>, // deprecated
pub name: Option<String>, pub name: Option<String>,
pub email: Option<String>, pub email: Option<String>,
pub password: Option<String>, pub password: Option<String>,
@ -54,7 +54,7 @@ impl UserTableChangeset {
pub fn new(params: UpdateUserParams) -> Self { pub fn new(params: UpdateUserParams) -> Self {
UserTableChangeset { UserTableChangeset {
id: params.id, id: params.id,
workspace: params.workspace, workspace: None,
name: params.name, name: params.name,
email: params.email, email: params.email,
password: params.password, password: params.password,

View File

@ -4,32 +4,34 @@ use std::convert::TryInto;
#[derive(Default, ProtoBuf)] #[derive(Default, ProtoBuf)]
pub struct QueryWorkspaceRequest { pub struct QueryWorkspaceRequest {
#[pb(index = 1)] #[pb(index = 1, one_of)]
pub workspace_id: String, pub workspace_id: Option<String>,
#[pb(index = 2)] #[pb(index = 2)]
pub read_apps: bool, pub user_id: String,
} }
// Read all workspaces if the workspace_id is None
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct QueryWorkspaceParams { pub struct QueryWorkspaceParams {
#[pb(index = 1)] #[pb(index = 1, one_of)]
pub workspace_id: String, pub workspace_id: Option<String>,
#[pb(index = 2)] #[pb(index = 2)]
pub read_apps: bool, pub user_id: String,
} }
impl QueryWorkspaceParams { impl QueryWorkspaceParams {
pub fn new(workspace_id: &str) -> Self { pub fn new(user_id: &str) -> Self {
Self { Self {
workspace_id: workspace_id.to_owned(), workspace_id: None,
user_id: user_id.to_owned(),
..Default::default() ..Default::default()
} }
} }
pub fn read_apps(mut self) -> Self { pub fn workspace_id(mut self, workspace_id: &str) -> Self {
self.read_apps = true; self.workspace_id = Some(workspace_id.to_string());
self self
} }
} }
@ -38,17 +40,22 @@ impl TryInto<QueryWorkspaceParams> for QueryWorkspaceRequest {
type Error = WorkspaceError; type Error = WorkspaceError;
fn try_into(self) -> Result<QueryWorkspaceParams, Self::Error> { fn try_into(self) -> Result<QueryWorkspaceParams, Self::Error> {
let workspace_id = WorkspaceId::parse(self.workspace_id) let workspace_id = match self.workspace_id {
.map_err(|e| { None => None,
ErrorBuilder::new(WsErrCode::WorkspaceIdInvalid) Some(workspace_id) => Some(
.msg(e) WorkspaceId::parse(workspace_id)
.build() .map_err(|e| {
})? ErrorBuilder::new(WsErrCode::WorkspaceIdInvalid)
.0; .msg(e)
.build()
})?
.0,
),
};
Ok(QueryWorkspaceParams { Ok(QueryWorkspaceParams {
workspace_id, workspace_id,
read_apps: self.read_apps, user_id: self.user_id,
}) })
} }
} }

View File

@ -3,8 +3,5 @@ use flowy_derive::ProtoBuf;
#[derive(ProtoBuf, Default, Debug)] #[derive(ProtoBuf, Default, Debug)]
pub struct CurrentWorkspace { pub struct CurrentWorkspace {
#[pb(index = 1)] #[pb(index = 1)]
pub owner: String,
#[pb(index = 2)]
pub workspace_id: String, pub workspace_id: String,
} }

View File

@ -21,9 +21,13 @@ pub enum WorkspaceEvent {
DeleteWorkspace = 3, DeleteWorkspace = 3,
#[display(fmt = "ReadAllWorkspace")] #[display(fmt = "ReadAllWorkspace")]
#[event(output = "Workspaces")] #[event(output = "RepeatedWorkspace")]
ReadAllWorkspace = 4, ReadAllWorkspace = 4,
#[display(fmt = "OpenWorkspace")]
#[event(input = "QueryWorkspaceRequest", output = "Workspace")]
OpenWorkspace = 5,
#[display(fmt = "CreateApp")] #[display(fmt = "CreateApp")]
#[event(input = "CreateAppRequest", output = "App")] #[event(input = "CreateAppRequest", output = "App")]
CreateApp = 101, CreateApp = 101,

View File

@ -29,16 +29,24 @@ pub async fn read_cur_workspace(
pub async fn read_workspace( pub async fn read_workspace(
data: Data<QueryWorkspaceRequest>, data: Data<QueryWorkspaceRequest>,
controller: Unit<Arc<WorkspaceController>>, controller: Unit<Arc<WorkspaceController>>,
) -> DataResult<Workspace, WorkspaceError> { ) -> DataResult<RepeatedWorkspace, WorkspaceError> {
let params: QueryWorkspaceParams = data.into_inner().try_into()?; let params: QueryWorkspaceParams = data.into_inner().try_into()?;
let mut workspace = controller.read_workspace(&params.workspace_id).await?;
if params.read_apps { let workspaces = controller.read_workspaces(params.workspace_id).await?;
let apps = controller.read_apps(&params.workspace_id).await?;
workspace.apps = RepeatedApp { items: apps };
}
data_result(workspace) data_result(workspaces)
}
#[tracing::instrument(name = "open_workspace", skip(data, controller))]
pub async fn open_workspace(
data: Data<QueryWorkspaceRequest>,
controller: Unit<Arc<WorkspaceController>>,
) -> DataResult<RepeatedWorkspace, WorkspaceError> {
let params: QueryWorkspaceParams = data.into_inner().try_into()?;
let workspaces = controller.open_workspace(params.workspace_id).await?;
data_result(workspaces)
} }
#[tracing::instrument(name = "get_all_workspaces", skip(controller))] #[tracing::instrument(name = "get_all_workspaces", skip(controller))]

View File

@ -47,7 +47,8 @@ pub fn create(user: Arc<dyn WorkspaceUser>, database: Arc<dyn WorkspaceDatabase>
.event(WorkspaceEvent::ReadAllWorkspace, read_all_workspaces) .event(WorkspaceEvent::ReadAllWorkspace, read_all_workspaces)
.event(WorkspaceEvent::CreateWorkspace, create_workspace) .event(WorkspaceEvent::CreateWorkspace, create_workspace)
.event(WorkspaceEvent::ReadCurWorkspace, read_cur_workspace) .event(WorkspaceEvent::ReadCurWorkspace, read_cur_workspace)
.event(WorkspaceEvent::ReadWorkspace, read_workspace); .event(WorkspaceEvent::ReadWorkspace, read_workspace)
.event(WorkspaceEvent::OpenWorkspace, open_workspace);
module = module module = module
.event(WorkspaceEvent::CreateApp, create_app) .event(WorkspaceEvent::CreateApp, create_app)

View File

@ -26,8 +26,9 @@
#[derive(PartialEq,Clone,Default)] #[derive(PartialEq,Clone,Default)]
pub struct QueryWorkspaceRequest { pub struct QueryWorkspaceRequest {
// message fields // message fields
pub workspace_id: ::std::string::String, pub user_id: ::std::string::String,
pub read_apps: bool, // message oneof groups
pub one_of_workspace_id: ::std::option::Option<QueryWorkspaceRequest_oneof_one_of_workspace_id>,
// special fields // special fields
pub unknown_fields: ::protobuf::UnknownFields, pub unknown_fields: ::protobuf::UnknownFields,
pub cached_size: ::protobuf::CachedSize, pub cached_size: ::protobuf::CachedSize,
@ -39,6 +40,11 @@ impl<'a> ::std::default::Default for &'a QueryWorkspaceRequest {
} }
} }
#[derive(Clone,PartialEq,Debug)]
pub enum QueryWorkspaceRequest_oneof_one_of_workspace_id {
workspace_id(::std::string::String),
}
impl QueryWorkspaceRequest { impl QueryWorkspaceRequest {
pub fn new() -> QueryWorkspaceRequest { pub fn new() -> QueryWorkspaceRequest {
::std::default::Default::default() ::std::default::Default::default()
@ -48,41 +54,75 @@ impl QueryWorkspaceRequest {
pub fn get_workspace_id(&self) -> &str { pub fn get_workspace_id(&self) -> &str {
&self.workspace_id match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(ref v)) => v,
_ => "",
}
} }
pub fn clear_workspace_id(&mut self) { pub fn clear_workspace_id(&mut self) {
self.workspace_id.clear(); self.one_of_workspace_id = ::std::option::Option::None;
}
pub fn has_workspace_id(&self) -> bool {
match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(..)) => true,
_ => false,
}
} }
// Param is passed by value, moved // Param is passed by value, moved
pub fn set_workspace_id(&mut self, v: ::std::string::String) { pub fn set_workspace_id(&mut self, v: ::std::string::String) {
self.workspace_id = v; self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(v))
} }
// Mutable pointer to the field. // Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_workspace_id(&mut self) -> &mut ::std::string::String { pub fn mut_workspace_id(&mut self) -> &mut ::std::string::String {
&mut self.workspace_id if let ::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(_)) = self.one_of_workspace_id {
} else {
self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(::std::string::String::new()));
}
match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(ref mut v)) => v,
_ => panic!(),
}
} }
// Take field // Take field
pub fn take_workspace_id(&mut self) -> ::std::string::String { pub fn take_workspace_id(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.workspace_id, ::std::string::String::new()) if self.has_workspace_id() {
match self.one_of_workspace_id.take() {
::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(v)) => v,
_ => panic!(),
}
} else {
::std::string::String::new()
}
} }
// bool read_apps = 2; // string user_id = 2;
pub fn get_read_apps(&self) -> bool { pub fn get_user_id(&self) -> &str {
self.read_apps &self.user_id
} }
pub fn clear_read_apps(&mut self) { pub fn clear_user_id(&mut self) {
self.read_apps = false; self.user_id.clear();
} }
// Param is passed by value, moved // Param is passed by value, moved
pub fn set_read_apps(&mut self, v: bool) { pub fn set_user_id(&mut self, v: ::std::string::String) {
self.read_apps = v; self.user_id = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_user_id(&mut self) -> &mut ::std::string::String {
&mut self.user_id
}
// Take field
pub fn take_user_id(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.user_id, ::std::string::String::new())
} }
} }
@ -96,14 +136,13 @@ impl ::protobuf::Message for QueryWorkspaceRequest {
let (field_number, wire_type) = is.read_tag_unpack()?; let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number { match field_number {
1 => { 1 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace_id)?; if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
},
2 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
} }
let tmp = is.read_bool()?; self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(is.read_string()?));
self.read_apps = tmp; },
2 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.user_id)?;
}, },
_ => { _ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
@ -117,11 +156,15 @@ impl ::protobuf::Message for QueryWorkspaceRequest {
#[allow(unused_variables)] #[allow(unused_variables)]
fn compute_size(&self) -> u32 { fn compute_size(&self) -> u32 {
let mut my_size = 0; let mut my_size = 0;
if !self.workspace_id.is_empty() { if !self.user_id.is_empty() {
my_size += ::protobuf::rt::string_size(1, &self.workspace_id); my_size += ::protobuf::rt::string_size(2, &self.user_id);
} }
if self.read_apps != false { if let ::std::option::Option::Some(ref v) = self.one_of_workspace_id {
my_size += 2; match v {
&QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(ref v) => {
my_size += ::protobuf::rt::string_size(1, &v);
},
};
} }
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size); self.cached_size.set(my_size);
@ -129,11 +172,15 @@ impl ::protobuf::Message for QueryWorkspaceRequest {
} }
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
if !self.workspace_id.is_empty() { if !self.user_id.is_empty() {
os.write_string(1, &self.workspace_id)?; os.write_string(2, &self.user_id)?;
} }
if self.read_apps != false { if let ::std::option::Option::Some(ref v) = self.one_of_workspace_id {
os.write_bool(2, self.read_apps)?; match v {
&QueryWorkspaceRequest_oneof_one_of_workspace_id::workspace_id(ref v) => {
os.write_string(1, v)?;
},
};
} }
os.write_unknown_fields(self.get_unknown_fields())?; os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(()) ::std::result::Result::Ok(())
@ -173,15 +220,15 @@ impl ::protobuf::Message for QueryWorkspaceRequest {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| { descriptor.get(|| {
let mut fields = ::std::vec::Vec::new(); let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( fields.push(::protobuf::reflect::accessor::make_singular_string_accessor::<_>(
"workspace_id", "workspace_id",
|m: &QueryWorkspaceRequest| { &m.workspace_id }, QueryWorkspaceRequest::has_workspace_id,
|m: &mut QueryWorkspaceRequest| { &mut m.workspace_id }, QueryWorkspaceRequest::get_workspace_id,
)); ));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBool>( fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"read_apps", "user_id",
|m: &QueryWorkspaceRequest| { &m.read_apps }, |m: &QueryWorkspaceRequest| { &m.user_id },
|m: &mut QueryWorkspaceRequest| { &mut m.read_apps }, |m: &mut QueryWorkspaceRequest| { &mut m.user_id },
)); ));
::protobuf::reflect::MessageDescriptor::new_pb_name::<QueryWorkspaceRequest>( ::protobuf::reflect::MessageDescriptor::new_pb_name::<QueryWorkspaceRequest>(
"QueryWorkspaceRequest", "QueryWorkspaceRequest",
@ -199,8 +246,8 @@ impl ::protobuf::Message for QueryWorkspaceRequest {
impl ::protobuf::Clear for QueryWorkspaceRequest { impl ::protobuf::Clear for QueryWorkspaceRequest {
fn clear(&mut self) { fn clear(&mut self) {
self.workspace_id.clear(); self.one_of_workspace_id = ::std::option::Option::None;
self.read_apps = false; self.user_id.clear();
self.unknown_fields.clear(); self.unknown_fields.clear();
} }
} }
@ -220,8 +267,9 @@ impl ::protobuf::reflect::ProtobufValue for QueryWorkspaceRequest {
#[derive(PartialEq,Clone,Default)] #[derive(PartialEq,Clone,Default)]
pub struct QueryWorkspaceParams { pub struct QueryWorkspaceParams {
// message fields // message fields
pub workspace_id: ::std::string::String, pub user_id: ::std::string::String,
pub read_apps: bool, // message oneof groups
pub one_of_workspace_id: ::std::option::Option<QueryWorkspaceParams_oneof_one_of_workspace_id>,
// special fields // special fields
pub unknown_fields: ::protobuf::UnknownFields, pub unknown_fields: ::protobuf::UnknownFields,
pub cached_size: ::protobuf::CachedSize, pub cached_size: ::protobuf::CachedSize,
@ -233,6 +281,11 @@ impl<'a> ::std::default::Default for &'a QueryWorkspaceParams {
} }
} }
#[derive(Clone,PartialEq,Debug)]
pub enum QueryWorkspaceParams_oneof_one_of_workspace_id {
workspace_id(::std::string::String),
}
impl QueryWorkspaceParams { impl QueryWorkspaceParams {
pub fn new() -> QueryWorkspaceParams { pub fn new() -> QueryWorkspaceParams {
::std::default::Default::default() ::std::default::Default::default()
@ -242,41 +295,75 @@ impl QueryWorkspaceParams {
pub fn get_workspace_id(&self) -> &str { pub fn get_workspace_id(&self) -> &str {
&self.workspace_id match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(ref v)) => v,
_ => "",
}
} }
pub fn clear_workspace_id(&mut self) { pub fn clear_workspace_id(&mut self) {
self.workspace_id.clear(); self.one_of_workspace_id = ::std::option::Option::None;
}
pub fn has_workspace_id(&self) -> bool {
match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(..)) => true,
_ => false,
}
} }
// Param is passed by value, moved // Param is passed by value, moved
pub fn set_workspace_id(&mut self, v: ::std::string::String) { pub fn set_workspace_id(&mut self, v: ::std::string::String) {
self.workspace_id = v; self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(v))
} }
// Mutable pointer to the field. // Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_workspace_id(&mut self) -> &mut ::std::string::String { pub fn mut_workspace_id(&mut self) -> &mut ::std::string::String {
&mut self.workspace_id if let ::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(_)) = self.one_of_workspace_id {
} else {
self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(::std::string::String::new()));
}
match self.one_of_workspace_id {
::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(ref mut v)) => v,
_ => panic!(),
}
} }
// Take field // Take field
pub fn take_workspace_id(&mut self) -> ::std::string::String { pub fn take_workspace_id(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.workspace_id, ::std::string::String::new()) if self.has_workspace_id() {
match self.one_of_workspace_id.take() {
::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(v)) => v,
_ => panic!(),
}
} else {
::std::string::String::new()
}
} }
// bool read_apps = 2; // string user_id = 2;
pub fn get_read_apps(&self) -> bool { pub fn get_user_id(&self) -> &str {
self.read_apps &self.user_id
} }
pub fn clear_read_apps(&mut self) { pub fn clear_user_id(&mut self) {
self.read_apps = false; self.user_id.clear();
} }
// Param is passed by value, moved // Param is passed by value, moved
pub fn set_read_apps(&mut self, v: bool) { pub fn set_user_id(&mut self, v: ::std::string::String) {
self.read_apps = v; self.user_id = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_user_id(&mut self) -> &mut ::std::string::String {
&mut self.user_id
}
// Take field
pub fn take_user_id(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.user_id, ::std::string::String::new())
} }
} }
@ -290,14 +377,13 @@ impl ::protobuf::Message for QueryWorkspaceParams {
let (field_number, wire_type) = is.read_tag_unpack()?; let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number { match field_number {
1 => { 1 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace_id)?; if wire_type != ::protobuf::wire_format::WireTypeLengthDelimited {
},
2 => {
if wire_type != ::protobuf::wire_format::WireTypeVarint {
return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type));
} }
let tmp = is.read_bool()?; self.one_of_workspace_id = ::std::option::Option::Some(QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(is.read_string()?));
self.read_apps = tmp; },
2 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.user_id)?;
}, },
_ => { _ => {
::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?;
@ -311,11 +397,15 @@ impl ::protobuf::Message for QueryWorkspaceParams {
#[allow(unused_variables)] #[allow(unused_variables)]
fn compute_size(&self) -> u32 { fn compute_size(&self) -> u32 {
let mut my_size = 0; let mut my_size = 0;
if !self.workspace_id.is_empty() { if !self.user_id.is_empty() {
my_size += ::protobuf::rt::string_size(1, &self.workspace_id); my_size += ::protobuf::rt::string_size(2, &self.user_id);
} }
if self.read_apps != false { if let ::std::option::Option::Some(ref v) = self.one_of_workspace_id {
my_size += 2; match v {
&QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(ref v) => {
my_size += ::protobuf::rt::string_size(1, &v);
},
};
} }
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size); self.cached_size.set(my_size);
@ -323,11 +413,15 @@ impl ::protobuf::Message for QueryWorkspaceParams {
} }
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
if !self.workspace_id.is_empty() { if !self.user_id.is_empty() {
os.write_string(1, &self.workspace_id)?; os.write_string(2, &self.user_id)?;
} }
if self.read_apps != false { if let ::std::option::Option::Some(ref v) = self.one_of_workspace_id {
os.write_bool(2, self.read_apps)?; match v {
&QueryWorkspaceParams_oneof_one_of_workspace_id::workspace_id(ref v) => {
os.write_string(1, v)?;
},
};
} }
os.write_unknown_fields(self.get_unknown_fields())?; os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(()) ::std::result::Result::Ok(())
@ -367,15 +461,15 @@ impl ::protobuf::Message for QueryWorkspaceParams {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| { descriptor.get(|| {
let mut fields = ::std::vec::Vec::new(); let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( fields.push(::protobuf::reflect::accessor::make_singular_string_accessor::<_>(
"workspace_id", "workspace_id",
|m: &QueryWorkspaceParams| { &m.workspace_id }, QueryWorkspaceParams::has_workspace_id,
|m: &mut QueryWorkspaceParams| { &mut m.workspace_id }, QueryWorkspaceParams::get_workspace_id,
)); ));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBool>( fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"read_apps", "user_id",
|m: &QueryWorkspaceParams| { &m.read_apps }, |m: &QueryWorkspaceParams| { &m.user_id },
|m: &mut QueryWorkspaceParams| { &mut m.read_apps }, |m: &mut QueryWorkspaceParams| { &mut m.user_id },
)); ));
::protobuf::reflect::MessageDescriptor::new_pb_name::<QueryWorkspaceParams>( ::protobuf::reflect::MessageDescriptor::new_pb_name::<QueryWorkspaceParams>(
"QueryWorkspaceParams", "QueryWorkspaceParams",
@ -393,8 +487,8 @@ impl ::protobuf::Message for QueryWorkspaceParams {
impl ::protobuf::Clear for QueryWorkspaceParams { impl ::protobuf::Clear for QueryWorkspaceParams {
fn clear(&mut self) { fn clear(&mut self) {
self.workspace_id.clear(); self.one_of_workspace_id = ::std::option::Option::None;
self.read_apps = false; self.user_id.clear();
self.unknown_fields.clear(); self.unknown_fields.clear();
} }
} }
@ -412,25 +506,28 @@ impl ::protobuf::reflect::ProtobufValue for QueryWorkspaceParams {
} }
static file_descriptor_proto_data: &'static [u8] = b"\ static file_descriptor_proto_data: &'static [u8] = b"\
\n\x15workspace_query.proto\"W\n\x15QueryWorkspaceRequest\x12!\n\x0cwork\ \n\x15workspace_query.proto\"l\n\x15QueryWorkspaceRequest\x12#\n\x0cwork\
space_id\x18\x01\x20\x01(\tR\x0bworkspaceId\x12\x1b\n\tread_apps\x18\x02\ space_id\x18\x01\x20\x01(\tH\0R\x0bworkspaceId\x12\x17\n\x07user_id\x18\
\x20\x01(\x08R\x08readApps\"V\n\x14QueryWorkspaceParams\x12!\n\x0cworksp\ \x02\x20\x01(\tR\x06userIdB\x15\n\x13one_of_workspace_id\"k\n\x14QueryWo\
ace_id\x18\x01\x20\x01(\tR\x0bworkspaceId\x12\x1b\n\tread_apps\x18\x02\ rkspaceParams\x12#\n\x0cworkspace_id\x18\x01\x20\x01(\tH\0R\x0bworkspace\
\x20\x01(\x08R\x08readAppsJ\x9e\x02\n\x06\x12\x04\0\0\t\x01\n\x08\n\x01\ Id\x12\x17\n\x07user_id\x18\x02\x20\x01(\tR\x06userIdB\x15\n\x13one_of_w\
\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\ orkspace_idJ\xd4\x02\n\x06\x12\x04\0\0\t\x01\n\x08\n\x01\x0c\x12\x03\0\0\
\0\x01\x12\x03\x02\x08\x1d\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x1c\n\ \x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\
\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\ \x02\x08\x1d\n\x0b\n\x04\x04\0\x08\0\x12\x03\x03\x04:\n\x0c\n\x05\x04\0\
\x12\x03\x03\x0b\x17\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x1a\x1b\n\ \x08\0\x01\x12\x03\x03\n\x1d\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x208\n\
\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x17\n\x0c\n\x05\x04\0\x02\x01\ \x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x20&\n\x0c\n\x05\x04\0\x02\0\x01\
\x05\x12\x03\x04\x04\x08\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\t\x12\ \x12\x03\x03'3\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x0367\n\x0b\n\x04\x04\
\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x15\x16\n\n\n\x02\x04\x01\x12\ \0\x02\x01\x12\x03\x04\x04\x17\n\x0c\n\x05\x04\0\x02\x01\x05\x12\x03\x04\
\x04\x06\0\t\x01\n\n\n\x03\x04\x01\x01\x12\x03\x06\x08\x1c\n\x0b\n\x04\ \x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x12\n\x0c\n\x05\x04\
\x04\x01\x02\0\x12\x03\x07\x04\x1c\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03\ \0\x02\x01\x03\x12\x03\x04\x15\x16\n\n\n\x02\x04\x01\x12\x04\x06\0\t\x01\
\x07\x04\n\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x07\x0b\x17\n\x0c\n\x05\ \n\n\n\x03\x04\x01\x01\x12\x03\x06\x08\x1c\n\x0b\n\x04\x04\x01\x08\0\x12\
\x04\x01\x02\0\x03\x12\x03\x07\x1a\x1b\n\x0b\n\x04\x04\x01\x02\x01\x12\ \x03\x07\x04:\n\x0c\n\x05\x04\x01\x08\0\x01\x12\x03\x07\n\x1d\n\x0b\n\
\x03\x08\x04\x17\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\x03\x08\x04\x08\n\ \x04\x04\x01\x02\0\x12\x03\x07\x208\n\x0c\n\x05\x04\x01\x02\0\x05\x12\
\x0c\n\x05\x04\x01\x02\x01\x01\x12\x03\x08\t\x12\n\x0c\n\x05\x04\x01\x02\ \x03\x07\x20&\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03\x07'3\n\x0c\n\x05\
\x01\x03\x12\x03\x08\x15\x16b\x06proto3\ \x04\x01\x02\0\x03\x12\x03\x0767\n\x0b\n\x04\x04\x01\x02\x01\x12\x03\x08\
\x04\x17\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\x03\x08\x04\n\n\x0c\n\x05\
\x04\x01\x02\x01\x01\x12\x03\x08\x0b\x12\n\x0c\n\x05\x04\x01\x02\x01\x03\
\x12\x03\x08\x15\x16b\x06proto3\
"; ";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT;

View File

@ -26,7 +26,6 @@
#[derive(PartialEq,Clone,Default)] #[derive(PartialEq,Clone,Default)]
pub struct CurrentWorkspace { pub struct CurrentWorkspace {
// message fields // message fields
pub owner: ::std::string::String,
pub workspace_id: ::std::string::String, pub workspace_id: ::std::string::String,
// special fields // special fields
pub unknown_fields: ::protobuf::UnknownFields, pub unknown_fields: ::protobuf::UnknownFields,
@ -44,33 +43,7 @@ impl CurrentWorkspace {
::std::default::Default::default() ::std::default::Default::default()
} }
// string owner = 1; // string workspace_id = 1;
pub fn get_owner(&self) -> &str {
&self.owner
}
pub fn clear_owner(&mut self) {
self.owner.clear();
}
// Param is passed by value, moved
pub fn set_owner(&mut self, v: ::std::string::String) {
self.owner = v;
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_owner(&mut self) -> &mut ::std::string::String {
&mut self.owner
}
// Take field
pub fn take_owner(&mut self) -> ::std::string::String {
::std::mem::replace(&mut self.owner, ::std::string::String::new())
}
// string workspace_id = 2;
pub fn get_workspace_id(&self) -> &str { pub fn get_workspace_id(&self) -> &str {
@ -107,9 +80,6 @@ impl ::protobuf::Message for CurrentWorkspace {
let (field_number, wire_type) = is.read_tag_unpack()?; let (field_number, wire_type) = is.read_tag_unpack()?;
match field_number { match field_number {
1 => { 1 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.owner)?;
},
2 => {
::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace_id)?; ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.workspace_id)?;
}, },
_ => { _ => {
@ -124,11 +94,8 @@ impl ::protobuf::Message for CurrentWorkspace {
#[allow(unused_variables)] #[allow(unused_variables)]
fn compute_size(&self) -> u32 { fn compute_size(&self) -> u32 {
let mut my_size = 0; let mut my_size = 0;
if !self.owner.is_empty() {
my_size += ::protobuf::rt::string_size(1, &self.owner);
}
if !self.workspace_id.is_empty() { if !self.workspace_id.is_empty() {
my_size += ::protobuf::rt::string_size(2, &self.workspace_id); my_size += ::protobuf::rt::string_size(1, &self.workspace_id);
} }
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size); self.cached_size.set(my_size);
@ -136,11 +103,8 @@ impl ::protobuf::Message for CurrentWorkspace {
} }
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> {
if !self.owner.is_empty() {
os.write_string(1, &self.owner)?;
}
if !self.workspace_id.is_empty() { if !self.workspace_id.is_empty() {
os.write_string(2, &self.workspace_id)?; os.write_string(1, &self.workspace_id)?;
} }
os.write_unknown_fields(self.get_unknown_fields())?; os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(()) ::std::result::Result::Ok(())
@ -180,11 +144,6 @@ impl ::protobuf::Message for CurrentWorkspace {
static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT;
descriptor.get(|| { descriptor.get(|| {
let mut fields = ::std::vec::Vec::new(); let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"owner",
|m: &CurrentWorkspace| { &m.owner },
|m: &mut CurrentWorkspace| { &mut m.owner },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>(
"workspace_id", "workspace_id",
|m: &CurrentWorkspace| { &m.workspace_id }, |m: &CurrentWorkspace| { &m.workspace_id },
@ -206,7 +165,6 @@ impl ::protobuf::Message for CurrentWorkspace {
impl ::protobuf::Clear for CurrentWorkspace { impl ::protobuf::Clear for CurrentWorkspace {
fn clear(&mut self) { fn clear(&mut self) {
self.owner.clear();
self.workspace_id.clear(); self.workspace_id.clear();
self.unknown_fields.clear(); self.unknown_fields.clear();
} }
@ -225,16 +183,13 @@ impl ::protobuf::reflect::ProtobufValue for CurrentWorkspace {
} }
static file_descriptor_proto_data: &'static [u8] = b"\ static file_descriptor_proto_data: &'static [u8] = b"\
\n\x1bworkspace_user_detail.proto\"K\n\x10CurrentWorkspace\x12\x14\n\x05\ \n\x1bworkspace_user_detail.proto\"5\n\x10CurrentWorkspace\x12!\n\x0cwor\
owner\x18\x01\x20\x01(\tR\x05owner\x12!\n\x0cworkspace_id\x18\x02\x20\ kspace_id\x18\x01\x20\x01(\tR\x0bworkspaceIdJa\n\x06\x12\x04\0\0\x04\x01\
\x01(\tR\x0bworkspaceIdJ\x98\x01\n\x06\x12\x04\0\0\x05\x01\n\x08\n\x01\ \n\x08\n\x01\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x04\x01\n\
\x0c\x12\x03\0\0\x12\n\n\n\x02\x04\0\x12\x04\x02\0\x05\x01\n\n\n\x03\x04\ \n\n\x03\x04\0\x01\x12\x03\x02\x08\x18\n\x0b\n\x04\x04\0\x02\0\x12\x03\
\0\x01\x12\x03\x02\x08\x18\n\x0b\n\x04\x04\0\x02\0\x12\x03\x03\x04\x15\n\ \x03\x04\x1c\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\n\x05\
\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x03\x04\n\n\x0c\n\x05\x04\0\x02\0\x01\ \x04\0\x02\0\x01\x12\x03\x03\x0b\x17\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\
\x12\x03\x03\x0b\x10\n\x0c\n\x05\x04\0\x02\0\x03\x12\x03\x03\x13\x14\n\ \x03\x1a\x1bb\x06proto3\
\x0b\n\x04\x04\0\x02\x01\x12\x03\x04\x04\x1c\n\x0c\n\x05\x04\0\x02\x01\
\x05\x12\x03\x04\x04\n\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03\x04\x0b\x17\
\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03\x04\x1a\x1bb\x06proto3\
"; ";
static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT;

View File

@ -1,10 +1,10 @@
syntax = "proto3"; syntax = "proto3";
message QueryWorkspaceRequest { message QueryWorkspaceRequest {
string workspace_id = 1; oneof one_of_workspace_id { string workspace_id = 1; };
bool read_apps = 2; string user_id = 2;
} }
message QueryWorkspaceParams { message QueryWorkspaceParams {
string workspace_id = 1; oneof one_of_workspace_id { string workspace_id = 1; };
bool read_apps = 2; string user_id = 2;
} }

View File

@ -1,6 +1,5 @@
syntax = "proto3"; syntax = "proto3";
message CurrentWorkspace { message CurrentWorkspace {
string owner = 1; string workspace_id = 1;
string workspace_id = 2;
} }

View File

@ -64,7 +64,20 @@ impl WorkspaceController {
pub async fn read_cur_workspace(&self) -> Result<Workspace, WorkspaceError> { pub async fn read_cur_workspace(&self) -> Result<Workspace, WorkspaceError> {
let user_workspace = self.user.get_cur_workspace().await?; let user_workspace = self.user.get_cur_workspace().await?;
let workspace = self.read_workspace(&user_workspace.workspace_id).await?; let mut repeated_workspace = self
.read_workspaces(Some(user_workspace.workspace_id.clone()))
.await?;
if repeated_workspace.is_empty() {
return Err(ErrorBuilder::new(WsErrCode::RecordNotFound).build());
}
debug_assert_eq!(repeated_workspace.len(), 1);
let workspace = repeated_workspace
.drain(..1)
.collect::<Vec<Workspace>>()
.pop()
.unwrap();
Ok(workspace) Ok(workspace)
} }
@ -74,9 +87,31 @@ impl WorkspaceController {
Ok(apps) Ok(apps)
} }
pub async fn read_workspace(&self, workspace_id: &str) -> Result<Workspace, WorkspaceError> { pub async fn open_workspace(&self, workspace_id: &str) -> Result<Workspace, WorkspaceError> {
let workspace_table = self.read_workspace_table(workspace_id).await?; let user_id = self.user.user_id()?;
Ok(workspace_table.into()) let result = self
.read_workspace_table(Some(workspace_id.to_owned()), user_id)
.await?
.first();
match result {
None => Err(ErrorBuilder::new(WsErrCode::RecordNotFound).build()),
Some(workspace_table) => {
let workspace: Workspace = workspace_table.into();
Ok(workspace)
},
}
}
pub async fn read_workspaces(
&self,
workspace_id: Option<String>,
) -> Result<RepeatedWorkspace, WorkspaceError> {
let user_id = self.user.user_id()?;
let workspace_tables = self.read_workspace_table(workspace_id, user_id).await?;
let mut workspaces = vec![];
Ok(RepeatedWorkspace { items: workspaces })
} }
pub async fn read_workspaces_belong_to_user(&self) -> Result<Vec<Workspace>, WorkspaceError> { pub async fn read_workspaces_belong_to_user(&self) -> Result<Vec<Workspace>, WorkspaceError> {
@ -104,13 +139,14 @@ impl WorkspaceController {
fn read_workspace_table( fn read_workspace_table(
&self, &self,
workspace_id: &str, workspace_id: Option<String>,
) -> DispatchFuture<Result<WorkspaceTable, WorkspaceError>> { user_id: String,
) -> DispatchFuture<Result<Vec<WorkspaceTable>, WorkspaceError>> {
let sql = self.sql.clone(); let sql = self.sql.clone();
let workspace_id = workspace_id.to_owned(); let workspace_id = workspace_id.to_owned();
DispatchFuture { DispatchFuture {
fut: Box::pin(async move { fut: Box::pin(async move {
let workspace = sql.read_workspace(&workspace_id)?; let workspace = sql.read_workspaces(workspace_id, &user_id)?;
// TODO: fetch workspace from remote server // TODO: fetch workspace from remote server
Ok(workspace) Ok(workspace)
}), }),
@ -131,26 +167,20 @@ pub async fn create_workspace_request(
Ok(workspace) Ok(workspace)
} }
pub async fn read_workspace_request( pub async fn read_workspaces_request(
params: QueryWorkspaceParams, params: QueryWorkspaceParams,
url: &str, url: &str,
) -> Result<Option<Workspace>, WorkspaceError> { ) -> Result<RepeatedWorkspace, WorkspaceError> {
let result = HttpRequestBuilder::get(&url.to_owned()) let result = HttpRequestBuilder::get(&url.to_owned())
.protobuf(params)? .protobuf(params)?
.send() .send()
.await? .await?
.response::<Workspace>() .response::<RepeatedWorkspace>()
.await; .await;
match result { match result {
Ok(workspace) => Ok(Some(workspace)), Ok(repeated_workspace) => Ok(repeated_workspace),
Err(e) => { Err(e) => Err(e.into()),
if e.is_not_found() {
Ok(None)
} else {
Err(e.into())
}
},
} }
} }

View File

@ -24,12 +24,20 @@ impl WorkspaceSql {
Ok(()) Ok(())
} }
pub fn read_workspace(&self, workspace_id: &str) -> Result<WorkspaceTable, WorkspaceError> { pub fn read_workspaces(
let workspace = dsl::workspace_table &self,
.filter(workspace_table::id.eq(&workspace_id)) workspace_id: Option<String>,
.first::<WorkspaceTable>(&*(self.database.db_connection()?))?; user_id: &str,
) -> Result<Vec<WorkspaceTable>, WorkspaceError> {
let mut filter = dsl::workspace_table.filter(workspace_table::user_id.eq(user_id));
Ok(workspace) if let Some(workspace_id) = workspace_id {
filter.filter(workspace_table::id.eq(&workspace_id));
}
let workspaces = filter.load::<WorkspaceTable>(&*(self.database.db_connection()?))?;
Ok(workspaces)
} }
pub fn update_workspace( pub fn update_workspace(