From 611f1eb4a6ed932ff217c34994dd31b5ff480783 Mon Sep 17 00:00:00 2001 From: chuan6 Date: Wed, 6 Jun 2018 23:10:14 +0800 Subject: [PATCH] =?UTF-8?q?refactor(typings):=20=E6=94=B9=E5=96=84?= =?UTF-8?q?=E5=92=8C=E7=BA=A0=E6=AD=A3=E5=90=84=E7=A7=8D=20id=20=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=9A=84=E6=80=A7=E8=B4=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 各种 id 类型如:UserId, ProjectId, TaskId 等等,它们应该有下列性质: 1.可以赋给 string 类型(允许如:`const x: string = id as UserId`) 2.相互之间不可赋值(如遇 `const tid: TeamId = uid as UserId` 会报错, 需要手动强转) 3.string 不可以赋给它们(如遇 `const id: UserId = 'hello'` 会报错,需 要手动强转) 4.可以直接使用在对象 index 的位置 原来 `interface X extends String { kind?: 'X' }` 的实现,满足了2,但没 有满足1、3、4。 不满足1,导致当需要将 id 数据从带有场景上下文的业务代码传给不关心业务逻 辑而只是简单接受 string 的底层组件时,需要通过 `as string` 强转,如果 该信息包在一个对象结构里,那这个对象结构要么需要 `as any`,结果丢失所 有类型信息,要么底层组件的对应对象结构类型声明就需要添加类型参数(泛型 声明),结果增加冗长而意义不大的泛型声明。 不满足3,会漏掉很多类型检查,因为并不是任何 string 类型的值都可以赋 值给特定 id 类型的。 不满足4,有时通过把 id 作为 key,构建简易的字典对象时,就不得不麻烦地 在 [] 里写 `as string`。 新的写法是: `type X = string & { kind: 'X' }` 它能同时满足1、2、3、4。 参考: - https://codemix.com/opaque-types-in-javascript/ - https://github.com/Microsoft/TypeScript/issues/15807 - https://github.com/Microsoft/TypeScript/issues/4895 - https://github.com/Microsoft/TypeScript/issues/202 - https://github.com/Microsoft/TypeScript/blob/d9b93903c035e48c8da1d731332787f83efc4619/src/compiler/types.ts#L54 --- src/apis/event/utils.ts | 2 +- src/schemas/Event.ts | 2 +- src/schemas/Member.ts | 12 ++- src/schemas/TapDashboard.ts | 4 +- src/schemas/TapQuestion.ts | 4 +- src/schemas/UserMe.ts | 8 +- src/teambition.ts | 96 +++++++++---------- test/apis/customfieldlink.spec.ts | 5 +- test/apis/event/EventGenerator.spec.ts | 13 +-- test/apis/event/event.spec.ts | 11 ++- test/apis/file.spec.ts | 3 +- test/apis/like.spec.ts | 15 +-- test/apis/my.spec.ts | 3 +- test/apis/organization.spec.ts | 5 +- test/apis/post.spec.ts | 31 +++--- test/apis/project.spec.ts | 5 +- test/apis/scenariofieldconfig.spec.ts | 28 +++--- test/apis/search.spec.ts | 9 +- test/apis/tag.spec.ts | 8 +- test/apis/task.spec.ts | 3 +- test/fixtures/scenariofieldconfigs.fixture.ts | 10 +- test/net/asyncLoadRDB.ts | 19 ++-- 22 files changed, 149 insertions(+), 147 deletions(-) diff --git a/src/apis/event/utils.ts b/src/apis/event/utils.ts index c67e1dcd1..e00ca2be5 100644 --- a/src/apis/event/utils.ts +++ b/src/apis/event/utils.ts @@ -191,5 +191,5 @@ export function timeToDate(date: string, returnValue?: boolean) { * 使用该函数根据实例上的 _id 获得原 _id。 */ export const originEventId = (id: EventId): EventId => { - return id.split('_', 1)[0] + return id.split('_', 1)[0] as EventId } diff --git a/src/schemas/Event.ts b/src/schemas/Event.ts index 9b0682354..9d1ad9651 100644 --- a/src/schemas/Event.ts +++ b/src/schemas/Event.ts @@ -25,7 +25,7 @@ export interface EventSchema { endDate: string untilDate: string isAllDay: boolean - involveMembers: string [] + involveMembers: UserId[] _projectId: ProjectId _scenariofieldconfigId?: ScenarioFieldConfigId _sourceId: EventId diff --git a/src/schemas/Member.ts b/src/schemas/Member.ts index 48484b111..f238750ba 100644 --- a/src/schemas/Member.ts +++ b/src/schemas/Member.ts @@ -18,9 +18,9 @@ export interface MemberProfileSchema { teamIds: TeamId[] } -export interface MemberSchema { +export interface GeneralMemberSchema { _boundToObjectId: ProjectId | OrganizationId - _id: String // 兼容新(MemberId)和旧(UserId),当完成迁移,换为更准确的 MemberId + _id: string // 兼容新(MemberId)和旧(UserId),当完成迁移,换为更准确的 MemberId _memberId: MemberId _roleId: RoleId _userId: UserId @@ -52,11 +52,15 @@ export interface MemberSchema { website: string } -export interface LegacyMemberSchema extends MemberSchema { +export interface MemberSchema extends GeneralMemberSchema { + _id: MemberId +} + +export interface LegacyMemberSchema extends GeneralMemberSchema { _id: UserId } -const Schema: SchemaDef = { +const Schema: SchemaDef = { _boundToObjectId: { type: RDBType.STRING }, _id: { type: RDBType.STRING, primaryKey: true }, _memberId: { type: RDBType.STRING }, diff --git a/src/schemas/TapDashboard.ts b/src/schemas/TapDashboard.ts index 57c5b3b8c..065d2d9c1 100644 --- a/src/schemas/TapDashboard.ts +++ b/src/schemas/TapDashboard.ts @@ -29,9 +29,7 @@ export interface TapCoordination { size?: TapCoordSize } -export interface TapDashboardSectionId extends String { - kind?: 'TapDashboardSectionId' -} +export type TapDashboardSectionId = string & { kind: 'TapDashboardSectionId' } export interface TapDashboardSection { _id: TapDashboardSectionId diff --git a/src/schemas/TapQuestion.ts b/src/schemas/TapQuestion.ts index ad89719a0..2d3a3acd1 100644 --- a/src/schemas/TapQuestion.ts +++ b/src/schemas/TapQuestion.ts @@ -1,9 +1,7 @@ import { TapChartType } from './TapChart' import { TapGenericFilterResponse } from 'teambition-types' -export interface TapQuestionId extends String { - kind?: 'QuestionId' -} +export type TapQuestionId = string & { kind: 'TapQuestionId' } export interface TapQuestion { _id: TapQuestionId diff --git a/src/schemas/UserMe.ts b/src/schemas/UserMe.ts index 1fac0341a..4d1386fab 100644 --- a/src/schemas/UserMe.ts +++ b/src/schemas/UserMe.ts @@ -19,13 +19,9 @@ export interface UserPaymentPlan { status: string } -export interface StrikerToken extends String { - kind?: 'StrikerToken' -} +export type StrikerToken = string & { kind: 'StrikerToken' } -export interface TcmToken extends String { - kind?: 'TcmToken' -} +export type TcmToken = string & { kind: 'TcmToken' } export interface UserMe { _id: UserId diff --git a/src/teambition.ts b/src/teambition.ts index e41e3f27b..9026c5681 100644 --- a/src/teambition.ts +++ b/src/teambition.ts @@ -1,54 +1,54 @@ // id declare module 'teambition-types' { - export interface ActivenessId extends String { kind?: 'ActivenessId' } - export interface ActivityId extends String { kind?: 'ActivityId' } - export interface AdvancedCustomFieldId extends String { kind?: 'AdvancedCustomFieldId' } - export interface ApplicationId extends String { kind?: 'ApplicationId' } - export interface CollectionId extends String { kind?: 'CollectionId' } - export interface CustomFieldCategoryId extends String { kind?: 'CustomFieldCategoryId' } - export interface CustomFieldChoiceId extends String { kind?: 'CustomFieldChoiceId' } - export interface CustomFieldId extends String { kind?: 'CustomFieldId' } - export interface CustomFieldLinkId extends String { kind?: 'CustomFieldLinkId' } - export interface CustomFieldValueId extends String { kind?: 'CustomFieldValueId' } - export interface CustomRoleId extends String { kind?: 'CustomRoleId' } - export interface DashboardCardId extends String { kind?: 'DashboardCardId' } - export interface EntryCategoryId extends String { kind?: 'EntryCategoryId' } - export interface EntryId extends String { kind?: 'EntryId' } - export interface EventId extends String { kind?: 'EventId' } - export interface FeedbackId extends String { kind?: 'FeedbackId' } - export interface FileId extends String { kind?: 'FileId' } - export interface GroupId extends String { kind?: 'GroupId' } - export interface HomeActivityId extends String { kind?: 'HomeActivityId' } - export interface MemberId extends String { kind?: 'MemberId' } - export interface MessageId extends String { kind?: 'MessageId' } - export interface ObjectLinkId extends String { kind?: 'ObjectLinkId' } - export interface OrganizationId extends String { kind?: 'OrganizationId' } - export interface PostId extends String { kind?: 'PostId' } - export interface PreferenceId extends String { kind?: 'PreferenceId' } - export interface ProjectBoardId extends String { kind?: 'ProjectBoardId' } - export interface ProjectId extends String { kind?: 'ProjectId' } - export interface ProjectTagId extends String { kind?: 'ProjectTagId' } - export interface RoomId extends String { kind?: 'RoomId' } - export interface ScenarioFieldId extends String { kind?: 'ScenarioFieldId' } - export interface ScenarioFieldConfigId extends String { kind?: 'ScenarioFieldConfigId' } - export interface SmartGroupId extends String { kind?: 'SmartGroupId' } - export interface SprintId extends String { kind?: 'SprintId' } - export interface StageId extends String { kind?: 'StageId' } - export interface SubscribeId extends String { kind?: 'SubscribeId' } - export interface SubtaskId extends String { kind?: 'SubtaskId' } - export interface TagCategoryId extends String { kind?: 'TagCategoryId' } - export interface TagId extends String { kind?: 'TagId' } - export interface TapChartId extends String { kind?: 'TapChartId' } - export interface TapDashboardId extends String { kind?: 'TapDashboardId' } - export interface TaskflowId extends String { kind?: 'TaskflowId' } - export interface TaskflowStatusId extends String { kind?: 'TaskflowStatusId' } - export interface TaskId extends String { kind?: 'TaskId' } - export interface TasklistId extends String { kind?: 'TasklistId' } - export interface TeamId extends String { kind?: 'TeamId' } - export interface UserId extends String { kind?: 'UserId' } - export interface VersionId extends String { kind?: 'VersionId' } - export interface WorkId extends String { kind?: 'WorkId' } + export type ActivenessId = string & { kind: 'ActivenessId' } + export type ActivityId = string & { kind: 'ActivityId' } + export type AdvancedCustomFieldId = string & { kind: 'AdvancedCustomFieldId' } + export type ApplicationId = string & { kind: 'ApplicationId' } + export type CollectionId = string & { kind: 'CollectionId' } + export type CustomFieldCategoryId = string & { kind: 'CustomFieldCategoryId' } + export type CustomFieldChoiceId = string & { kind: 'CustomFieldChoiceId' } + export type CustomFieldId = string & { kind: 'CustomFieldId' } + export type CustomFieldLinkId = string & { kind: 'CustomFieldLinkId' } + export type CustomFieldValueId = string & { kind: 'CustomFieldValueId' } + export type CustomRoleId = string & { kind: 'CustomRoleId' } + export type DashboardCardId = string & { kind: 'DashboardCardId' } + export type EntryCategoryId = string & { kind: 'EntryCategoryId' } + export type EntryId = string & { kind: 'EntryId' } + export type EventId = string & { kind: 'EventId' } + export type FeedbackId = string & { kind: 'FeedbackId' } + export type FileId = string & { kind: 'FileId' } + export type GroupId = string & { kind: 'GroupId' } + export type HomeActivityId = string & { kind: 'HomeActivityId' } + export type MemberId = string & { kind: 'MemberId' } + export type MessageId = string & { kind: 'MessageId' } + export type ObjectLinkId = string & { kind: 'ObjectLinkId' } + export type OrganizationId = string & { kind: 'OrganizationId' } + export type PostId = string & { kind: 'PostId' } + export type PreferenceId = string & { kind: 'PreferenceId' } + export type ProjectBoardId = string & { kind: 'ProjectBoardId' } + export type ProjectId = string & { kind: 'ProjectId' } + export type ProjectTagId = string & { kind: 'ProjectTagId' } + export type RoomId = string & { kind: 'RoomId' } + export type ScenarioFieldId = string & { kind: 'ScenarioFieldId' } + export type ScenarioFieldConfigId = string & { kind: 'ScenarioFieldConfigId' } + export type SmartGroupId = string & { kind: 'SmartGroupId' } + export type SprintId = string & { kind: 'SprintId' } + export type StageId = string & { kind: 'StageId' } + export type SubscribeId = string & { kind: 'SubscribeId' } + export type SubtaskId = string & { kind: 'SubtaskId' } + export type TagCategoryId = string & { kind: 'TagCategoryId' } + export type TagId = string & { kind: 'TagId' } + export type TapChartId = string & { kind: 'TapChartId' } + export type TapDashboardId = string & { kind: 'TapDashboardId' } + export type TaskflowId = string & { kind: 'TaskflowId' } + export type TaskflowStatusId = string & { kind: 'TaskflowStatusId' } + export type TaskId = string & { kind: 'TaskId' } + export type TasklistId = string & { kind: 'TasklistId' } + export type TeamId = string & { kind: 'TeamId' } + export type UserId = string & { kind: 'UserId' } + export type VersionId = string & { kind: 'VersionId' } + export type WorkId = string & { kind: 'WorkId' } } // computed id diff --git a/test/apis/customfieldlink.spec.ts b/test/apis/customfieldlink.spec.ts index 43d103854..170505c5e 100644 --- a/test/apis/customfieldlink.spec.ts +++ b/test/apis/customfieldlink.spec.ts @@ -5,6 +5,7 @@ import { expect } from 'chai' import { SDKFetch, createSdk, SDK } from '../' import { customFieldLink } from '../fixtures/customfieldlinks.fixture' import { mock, expectToDeepEqualForFieldsOfTheExpected } from '../utils' +import { ProjectId } from 'teambition-types' const fetchMock = require('fetch-mock') @@ -29,7 +30,7 @@ describe('CustomFieldLinkApi request spec: ', () => { }) it('should return a CustomFieldLink array', function* () { - const projectId = customFieldLink._projectId + const projectId = customFieldLink._projectId as ProjectId const customFieldLinks = [customFieldLink] const url = `/projects/${projectId}/customfieldlinks?boundType=application&_=666` @@ -51,7 +52,7 @@ describe('CustomFieldLinkApi spec: ', () => { }) it('should return a CustomFieldLink array', function* () { - const projectId = customFieldLink._projectId + const projectId = customFieldLink._projectId as ProjectId const customFieldLinks = [customFieldLink] mockResponse(customFieldLinks) diff --git a/test/apis/event/EventGenerator.spec.ts b/test/apis/event/EventGenerator.spec.ts index 9a1d3baa5..506875dd8 100644 --- a/test/apis/event/EventGenerator.spec.ts +++ b/test/apis/event/EventGenerator.spec.ts @@ -10,6 +10,7 @@ import { } from '../../fixtures/events.fixture' import { EventGenerator } from '../../../src/apis/event/EventGenerator' import { clone } from '../../index' +import { EventId } from 'teambition-types' describe('EventGenerator spec', () => { let eventGenerator: EventGenerator @@ -297,31 +298,31 @@ describe('EventGenerator spec', () => { it('findByEventId() should work on a normal event', () => { const _eventGenerator = new EventGenerator(normalEvent as any) - const targetId = normalEvent._id + const targetId = normalEvent._id as EventId const invalidId = normalEvent._id + 'asdf' expect(_eventGenerator.findByEventId(targetId)).to.deep.equal(normalEvent) - expect(_eventGenerator.findByEventId(invalidId)).to.be.null + expect(_eventGenerator.findByEventId(invalidId as EventId)).to.be.null }) it('findByEventId() should return null for a recurrent event with an un-timestamped id', () => { - const targetId = recurrenceByMonth._id + const targetId = recurrenceByMonth._id as EventId expect(eventGenerator.findByEventId(targetId)).to.be.null }) it('findByEventId() should work on a recurrent event', () => { let timestamp = new Date(recurrenceByMonth.startDate).valueOf() - let targetId = recurrenceByMonth._id + '_' + timestamp + let targetId = recurrenceByMonth._id + '_' + timestamp as EventId expect(eventGenerator.findByEventId(targetId)).to.deep.equal(eventGenerator.next().value) timestamp = Moment(recurrenceByMonth.startDate).add(2, 'months').valueOf() - targetId = recurrenceByMonth._id + '_' + timestamp + targetId = (recurrenceByMonth._id + '_' + timestamp) as EventId eventGenerator.next() expect(eventGenerator.findByEventId(targetId)).to.deep.equal(eventGenerator.next().value) const timestampExDate = new Date(recurrenceStartAtAnExcludedDate.startDate).valueOf() - const targetIdExDate = recurrenceStartAtAnExcludedDate._id + '_' + timestampExDate + const targetIdExDate = recurrenceStartAtAnExcludedDate._id + '_' + timestampExDate as EventId const eventGeneratorExDate = new EventGenerator(recurrenceStartAtAnExcludedDate as any) expect(eventGeneratorExDate.findByEventId(targetIdExDate)).to.be.null }) diff --git a/test/apis/event/event.spec.ts b/test/apis/event/event.spec.ts index 7d22cbaf9..e02a0c9f0 100644 --- a/test/apis/event/event.spec.ts +++ b/test/apis/event/event.spec.ts @@ -4,6 +4,7 @@ import { expect } from 'chai' import { createSdk, SDK, SocketMock, EventSchema } from '../../index' import * as Fixture from '../../fixtures/events.fixture' import { mock, restore, equals, looseDeepEqual, clone } from '../../utils' +import { EventId } from 'teambition-types' describe('EventApi request spec', () => { let sdk: SDK @@ -22,7 +23,7 @@ describe('EventApi request spec', () => { const fixture = Fixture.normalEvent mockResponse(fixture) - yield sdk.getEvent(fixture._id) + yield sdk.getEvent(fixture._id as EventId) .values() .do(([r]) => { const result = r.next().value @@ -34,7 +35,7 @@ describe('EventApi request spec', () => { const fixture = Fixture.recurrenceByMonth mockResponse(fixture) - yield sdk.getEvent(fixture._id) + yield sdk.getEvent(fixture._id as EventId) .values() .do(([r]) => { const result = r.next().value @@ -58,7 +59,7 @@ describe('EventApi request spec', () => { const fixture = Fixture.recurrenceByMonth mockResponse(fixture) - const signal = sdk.getEvent(fixture._id) + const signal = sdk.getEvent(fixture._id as EventId) .changes() signal.subscribe() @@ -83,13 +84,13 @@ describe('EventApi request spec', () => { const fixture = Fixture.recurrenceByMonth mockResponse(fixture) - const token1 = sdk.getEvent(fixture._id) + const token1 = sdk.getEvent(fixture._id as EventId) const f2 = clone(fixture) f2._id = 'mockF2Id' mockResponse(f2) - const token2 = sdk.getEvent(f2._id) + const token2 = sdk.getEvent(f2._id as EventId) yield token1.combine(token2) .values() diff --git a/test/apis/file.spec.ts b/test/apis/file.spec.ts index b6dcf7185..20e835c23 100644 --- a/test/apis/file.spec.ts +++ b/test/apis/file.spec.ts @@ -3,6 +3,7 @@ import { expect } from 'chai' import { createSdk, SDK, SocketMock, FileSchema } from '../index' import * as Fixture from '../fixtures/files.fixture' import { mock, restore, looseDeepEqual, expectToDeepEqualForFieldsOfTheExpected } from '../utils' +import { FileId } from 'teambition-types' describe('FileApi request spec', () => { let sdk: SDK @@ -21,7 +22,7 @@ describe('FileApi request spec', () => { const [ fixture ] = Fixture.projectFiles mockResponse(fixture) - yield sdk.getFile(fixture._id) + yield sdk.getFile(fixture._id as FileId) .values() .do(([r]) => { expectToDeepEqualForFieldsOfTheExpected(r, fixture) diff --git a/test/apis/like.spec.ts b/test/apis/like.spec.ts index 6a6252cb3..86ea648cb 100644 --- a/test/apis/like.spec.ts +++ b/test/apis/like.spec.ts @@ -4,10 +4,13 @@ import { describe, it, beforeEach, afterEach } from 'tman' import { createSdk, SDK, LikeSchema } from '../index' import like from '../fixtures/like.fixture' import { mock, restore } from '../utils' +import { DetailObjectId } from 'teambition-types' describe('LikeApi request spec: ', () => { let sdk: SDK let mockResponse: (m: T, delay?: number | Promise) => void + const mockTaskId = 'mocktask' as DetailObjectId + const mockTaskLikeId = 'mocktask:like' beforeEach(() => { sdk = createSdk() @@ -21,7 +24,7 @@ describe('LikeApi request spec: ', () => { it('get like should pass', function* () { mockResponse(like) - yield sdk.getLike('task', 'mocktask') + yield sdk.getLike('task', mockTaskId) .values() .do(([r]) => { delete r._id @@ -32,15 +35,15 @@ describe('LikeApi request spec: ', () => { it('toggle like should pass', function* () { yield sdk.database.insert('Like', { ...like, - _id: 'mocktask:like' + _id: mockTaskLikeId }) mockResponse({ ...like, isLike: false }) - yield sdk.toggleLike('task', 'mocktask', true) + yield sdk.toggleLike('task', mockTaskId, true) yield sdk.database.get('Like', { - where: { _id: 'mocktask:like' } + where: { _id: mockTaskLikeId } }) .values() .do(([r]) => { @@ -49,10 +52,10 @@ describe('LikeApi request spec: ', () => { mockResponse({ ...like, isLike: true }) - yield sdk.toggleLike('task', 'mocktask', false) + yield sdk.toggleLike('task', mockTaskId, false) yield sdk.database.get('Like', { - where: { _id: 'mocktask:like' } + where: { _id: mockTaskLikeId } }) .values() .do(([r]) => { diff --git a/test/apis/my.spec.ts b/test/apis/my.spec.ts index 8878570f5..e6372f628 100644 --- a/test/apis/my.spec.ts +++ b/test/apis/my.spec.ts @@ -4,9 +4,10 @@ import { createSdk, SDK, TaskSchema } from '../index' import { EventGenerator } from '../../src/apis/event/EventGenerator' import * as Fixture from '../fixtures/my.fixture' import { mock, restore, expectToDeepEqualForFieldsOfTheExpected } from '../utils' +import { UserId } from 'teambition-types' describe('MyApi request spec', () => { - const userId = Fixture.myRecent[0]['_executorId'] + const userId = Fixture.myRecent[0]['_executorId'] as UserId let sdk: SDK let mockResponse: (m: T, delay?: number | Promise) => void diff --git a/test/apis/organization.spec.ts b/test/apis/organization.spec.ts index 3607e1cdc..b7537da70 100644 --- a/test/apis/organization.spec.ts +++ b/test/apis/organization.spec.ts @@ -9,6 +9,7 @@ import { getStarredOrganizationProjects, getUngroupedOrganizationProjects } from '../../src/apis/organization/projects' +import { OrganizationId, TagId } from 'teambition-types' const fetchMock = require('fetch-mock') @@ -17,7 +18,7 @@ describe('get organization projects', () => { let sdkFetch: SDKFetch let projects: any[] - const sampleOrgId = '56f0d51e3cd13a5b537c3a12' + const sampleOrgId = '56f0d51e3cd13a5b537c3a12' as OrganizationId const getOrganizationProjectsFns = () => [ { fn: getAllOrganizationProjects, namespace: 'all' }, { fn: getJoinedOrganizationProjects, namespace: 'joined' }, @@ -71,7 +72,7 @@ describe('get organization projects', () => { }) it('getOrganizationProjectByTagId should make correctly formatted request to target url and return response as it is', function* () { - const sampleTagId = '3' + const sampleTagId = '3' as TagId const expectedUrl = `/organizations/${sampleOrgId}/projecttags/${sampleTagId}/projects?_=666` const expectedResponse = projects.filter(({ tagId }) => tagId === sampleTagId) diff --git a/test/apis/post.spec.ts b/test/apis/post.spec.ts index f138a5a00..4d9f738d8 100644 --- a/test/apis/post.spec.ts +++ b/test/apis/post.spec.ts @@ -4,6 +4,7 @@ import { createSdk, SDK, PostSchema, SocketMock } from '../index' import { projectPosts, myProjectPosts, tagPosts } from '../fixtures/posts.fixture' import { mock, restore, equals } from '../utils' import { shuffle } from 'lodash' +import { PostId, ProjectId, TagId, UserId } from 'teambition-types' describe('PostApi request spec', () => { let sdk: SDK @@ -29,7 +30,7 @@ describe('PostApi request spec', () => { mockResponse(fixture) - yield sdk.getPost(fixture._id) + yield sdk.getPost(fixture._id as PostId) .values() .do(([r]) => { expect(r).to.deep.equal(fixture) @@ -37,7 +38,7 @@ describe('PostApi request spec', () => { }) it('getAllProjects should response correct data', function* () { - const projectId = projectPosts[0]._projectId + const projectId = projectPosts[0]._projectId as ProjectId const fixture = projectPosts.slice(0, 20) mockResponse(fixture) @@ -68,7 +69,7 @@ describe('PostApi request spec', () => { }) it('getAllProjects should response ordered data', function* () { - const projectId = projectPosts[0]._projectId + const projectId = projectPosts[0]._projectId as ProjectId const fixture = projectPosts.slice(0, 20) const unordered = shuffle(fixture) @@ -88,8 +89,8 @@ describe('PostApi request spec', () => { it('getMyProjectPosts should response correct data', function* () { const fixture = myProjectPosts.slice(0, 20) - const userId = fixture[0]._creatorId - const projectId = fixture[0]._projectId + const userId = fixture[0]._creatorId as UserId + const projectId = fixture[0]._projectId as ProjectId mockResponse(fixture) @@ -118,8 +119,8 @@ describe('PostApi request spec', () => { it('getMyProjectPosts should response ordered data', function* () { const fixture = myProjectPosts.slice(0, 20) - const userId = fixture[0]._creatorId - const projectId = fixture[0]._projectId + const userId = fixture[0]._creatorId as UserId + const projectId = fixture[0]._projectId as ProjectId const unordered = shuffle(fixture) mockResponse(unordered) @@ -137,7 +138,7 @@ describe('PostApi request spec', () => { }) it('getPostsByTagId should response correct data', function* () { - const fixture = '569de6be18bfe350733e2443' + const fixture = '569de6be18bfe350733e2443' as TagId mockResponse(tagPosts) @@ -150,7 +151,7 @@ describe('PostApi request spec', () => { }) it('getPostsByTagId should response ordered data', function* () { - const fixture = '569de6be18bfe350733e2443' + const fixture = '569de6be18bfe350733e2443' as TagId const unordered = shuffle(tagPosts) mockResponse(unordered) @@ -169,7 +170,7 @@ describe('PostApi request spec', () => { mockResponse(fixture) yield sdk.createPost({ - _projectId: fixture._projectId, + _projectId: fixture._projectId as ProjectId, title: fixture.title, content: fixture.content, tagIds: fixture.tagIds, @@ -189,7 +190,7 @@ describe('PostApi request spec', () => { yield sdk.database.insert('Post', placeholder) const fixture = { - _id: placeholder._id, + _id: placeholder._id as PostId, title: 'new title' } @@ -209,7 +210,7 @@ describe('PostApi request spec', () => { mockResponse({}) - yield sdk.deletePost(placeholder._id) + yield sdk.deletePost(placeholder._id as PostId) yield sdk.database.get('Post', { where: { _id: placeholder._id } }) .values() @@ -220,16 +221,10 @@ describe('PostApi request spec', () => { describe('PostsAPI socket spec', () => { let sdk: SDK let socket: SocketMock - let defaultOrderBy: any beforeEach(() => { sdk = createSdk() socket = new SocketMock(sdk.socketClient) - defaultOrderBy = [ - { fieldName: 'pin', orderBy: 'DESC' }, - { fieldName: 'created', orderBy: 'DESC' }, - { fieldName: 'lastCommentedAt', orderBy: 'DESC' } - ] }) afterEach(() => { diff --git a/test/apis/project.spec.ts b/test/apis/project.spec.ts index 81d08da46..fd0350d28 100644 --- a/test/apis/project.spec.ts +++ b/test/apis/project.spec.ts @@ -7,6 +7,7 @@ import { import { SDKFetch, createSdk, SDK } from '../' import { normalProject } from '../fixtures/projects.fixture' import { mock, expectToDeepEqualForFieldsOfTheExpected } from '../utils' +import { ProjectId } from 'teambition-types' const fetchMock = require('fetch-mock') @@ -108,7 +109,7 @@ describe('ProjectApi request spec: ', () => { it('getProject() should return a project', function* () { const project = normalProject - const projectId = project._id + const projectId = project._id as ProjectId const url = `/projects/${projectId}?_=666` fetchMock.getOnce(url, project) @@ -133,7 +134,7 @@ describe('ProjectApi spec: ', () => { const fixture = normalProject mockResponse(fixture) - yield sdk.getProject(fixture._id) + yield sdk.getProject(fixture._id as ProjectId) .values() .subscribeOn(Scheduler.asap) .do(([project]) => { diff --git a/test/apis/scenariofieldconfig.spec.ts b/test/apis/scenariofieldconfig.spec.ts index 082baa939..b12e40535 100644 --- a/test/apis/scenariofieldconfig.spec.ts +++ b/test/apis/scenariofieldconfig.spec.ts @@ -2,7 +2,7 @@ import { describe, before, beforeEach, afterEach, it, after } from 'tman' import { Scheduler } from 'rxjs' import { expect } from 'chai' -import { SDKFetch, createSdk, SDK } from '../' +import { SDKFetch, createSdk, SDK, ScenarioFieldConfigSchema } from '../' import { taskScenarioFieldConfig, eventScenarioFieldConfig, @@ -35,7 +35,7 @@ describe('ScenarioFieldConfigApi request spec: ', () => { }) it('should return a TaskScenarioFieldConfig array', function* () { - const projectId = taskScenarioFieldConfig._projectId + const projectId = taskScenarioFieldConfig._projectId as ProjectId const configs = [taskScenarioFieldConfig] const url = `/projects/${projectId}/scenariofieldconfigs?objectType=task&withTaskflowstatus=true&_=666` @@ -47,7 +47,7 @@ describe('ScenarioFieldConfigApi request spec: ', () => { }) it('should return an EventScenarioFieldConfig array', function* () { - const projectId = eventScenarioFieldConfig._projectId + const projectId = eventScenarioFieldConfig._projectId as ProjectId const configs = [eventScenarioFieldConfig] const url = `/projects/${projectId}/scenariofieldconfigs?objectType=event&withTaskflowstatus=true&_=666` @@ -146,7 +146,7 @@ describe('ScenarioFieldConfigApi request spec: ', () => { }) it('should return an array of Project using the ScenarioFieldConfig', function* () { - const sfcId = 'mock-sf-config-id' + const sfcId = 'mock-sf-config-id' as ScenarioFieldConfigId const resp = { totalSize: 10, result: ['p1', 'p2'] } fetchMock.once(`/scenariofieldconfigs/${sfcId}/projects?_=666`, resp) @@ -159,8 +159,8 @@ describe('ScenarioFieldConfigApi request spec: ', () => { }) it('should create a new ScenarioFieldConfig', function* () { - const configId = 'mock-sfc-id' - const config = { ...orgTaskScenarioFieldConfig, _id: configId } + const configId = 'mock-sfc-id' as ScenarioFieldConfigId + const config = { ...orgTaskScenarioFieldConfig, _id: configId } as any const orgId = config._boundToObjectId as OrganizationId fetchMock.postOnce(`/organizations/${orgId}/scenariofieldconfigs`, config) @@ -173,7 +173,7 @@ describe('ScenarioFieldConfigApi request spec: ', () => { }) it('should return Boolean as the validation result', function* () { - const orgId = 'mock-org-id' + const orgId = 'mock-org-id' as OrganizationId const objectType = 'task' const name = 'mock-sfc-name' const resp = { exists: true } @@ -202,7 +202,7 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should return a TaskScenarioFieldConfig array', function* () { - const projectId = taskScenarioFieldConfig._projectId + const projectId = taskScenarioFieldConfig._projectId as ProjectId const configs = [{ ...taskScenarioFieldConfig, taskflowstatuses: undefined }] mockResponse(configs) @@ -216,7 +216,7 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should return an EventScenarioFieldConfig array', function* () { - const projectId = eventScenarioFieldConfig._projectId + const projectId = eventScenarioFieldConfig._projectId as ProjectId const configs = [eventScenarioFieldConfig] mockResponse(configs) @@ -258,7 +258,7 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should add a TaskScenarioFieldConfig array to Project', function* () { - const configId = 'mock-task-sf-config-id' + const configId = 'mock-task-sf-config-id' as ScenarioFieldConfigId const config = { ...taskScenarioFieldConfig, _id: configId, taskflowstatuses: undefined } const projectId = config._boundToObjectId as ProjectId const configIds = [configId] @@ -288,7 +288,7 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should add an EventScenarioFieldConfig array to Project', function* () { - const configId = 'mock-event-sf-config-id' + const configId = 'mock-event-sf-config-id' as ScenarioFieldConfigId const config = { ...eventScenarioFieldConfig, _id: configId } const projectId = config._boundToObjectId as ProjectId const configIds = [configId] @@ -318,7 +318,7 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should restore ScenarioFieldConfig to the Base', function* () { - const configId = 'mock-event-sf-config-id' + const configId = 'mock-event-sf-config-id' as ScenarioFieldConfigId const config = { ...eventScenarioFieldConfig, _id: configId } const configBase = { ...config, name: 'mock-event-sf-config-name' } const projectId = config._boundToObjectId as ProjectId @@ -361,8 +361,8 @@ describe('ScenarioFieldConfigApi spec: ', () => { }) it('should create a new ScenarioFieldConfig', function* () { - const configId = 'mock-sfc-id' - const orgId = 'mock-org-id' + const configId = 'mock-sfc-id' as ScenarioFieldConfigId + const orgId = 'mock-org-id' as OrganizationId const objectType = 'task' const config = { _id: configId, _boundToObjectId: orgId, objectType } diff --git a/test/apis/search.spec.ts b/test/apis/search.spec.ts index a095d6ca6..8c584b4ef 100644 --- a/test/apis/search.spec.ts +++ b/test/apis/search.spec.ts @@ -10,6 +10,7 @@ import { buildPath as buildPathForMemberSearching } from '../../src/apis/search/members' import { SDKFetch } from '../' +import { GroupId, OrganizationId, ProjectId, TeamId } from 'teambition-types' const fetchMock = require('fetch-mock') @@ -33,22 +34,22 @@ describe('search for members', () => { const sampleId = '58de087921efc137f43cef3c' expect(buildPathForMemberSearching({ type: ScopeType.Team, - id: sampleId + id: sampleId as TeamId })).to.equal(`teams/${sampleId}/members/search`) expect(buildPathForMemberSearching({ type: ScopeType.Project, - id: sampleId + id: sampleId as ProjectId })).to.equal(`projects/${sampleId}/members/search`) expect(buildPathForMemberSearching({ type: ScopeType.Organization, - id: sampleId + id: sampleId as OrganizationId })).to.equal(`organizations/${sampleId}/members/search`) expect(buildPathForMemberSearching({ type: ScopeType.Group, - id: sampleId + id: sampleId as GroupId })).to.equal(`groups/${sampleId}/members/search`) }) }) diff --git a/test/apis/tag.spec.ts b/test/apis/tag.spec.ts index f7b3a56f9..7036971bb 100644 --- a/test/apis/tag.spec.ts +++ b/test/apis/tag.spec.ts @@ -30,7 +30,7 @@ describe('TagApi request spec: ', () => { }) it('should return a Project Tag array', function* () { - const projectId: ProjectId = projectTag._projectId + const projectId = projectTag._projectId as ProjectId const tags = [projectTag] const url = `/tags?tagType=project&_projectId=${projectId}&_=666` @@ -42,7 +42,7 @@ describe('TagApi request spec: ', () => { }) it('should return an Organization Tag array', function* () { - const orgId: OrganizationId = organizationTag._organizationId + const orgId = organizationTag._organizationId as OrganizationId const tags = [projectTag] const url = `/tags?tagType=organization&_organizationId=${orgId}&_=666` @@ -64,7 +64,7 @@ describe('TagApi spec: ', () => { }) it('should return a Project Tag array', function* () { - const projectId: ProjectId = projectTag._projectId + const projectId = projectTag._projectId as ProjectId const tags = [projectTag] mockResponse(tags) @@ -77,7 +77,7 @@ describe('TagApi spec: ', () => { }) it('should return an Organization Tag array', function* () { - const orgId: OrganizationId = organizationTag._organizationId + const orgId = organizationTag._organizationId as OrganizationId const tags = [organizationTag] mockResponse(tags) diff --git a/test/apis/task.spec.ts b/test/apis/task.spec.ts index 86bc57da4..2d9b50d63 100644 --- a/test/apis/task.spec.ts +++ b/test/apis/task.spec.ts @@ -3,6 +3,7 @@ import { expect } from 'chai' import { createSdk, SDK, SocketMock, TaskSchema } from '../index' import * as Fixture from '../fixtures/tasks.fixture' import { mock, restore, looseDeepEqual, expectToDeepEqualForFieldsOfTheExpected } from '../utils' +import { TaskId } from 'teambition-types' describe('TaskApi request Spec', () => { let sdk: SDK @@ -21,7 +22,7 @@ describe('TaskApi request Spec', () => { const fixture = Fixture.task mockResponse(fixture) - yield sdk.getTask(fixture._id) + yield sdk.getTask(fixture._id as TaskId) .values() .do(([r]) => { expectToDeepEqualForFieldsOfTheExpected(r, fixture, 'subtasks', 'ancestors') diff --git a/test/fixtures/scenariofieldconfigs.fixture.ts b/test/fixtures/scenariofieldconfigs.fixture.ts index 88358c79c..d9db7b77f 100644 --- a/test/fixtures/scenariofieldconfigs.fixture.ts +++ b/test/fixtures/scenariofieldconfigs.fixture.ts @@ -1,6 +1,4 @@ -import { TaskScenarioFieldConfigSchema, EventScenarioFieldConfigSchema } from '..' - -export const taskScenarioFieldConfig: TaskScenarioFieldConfigSchema = { +export const taskScenarioFieldConfig = { _id: '5a977492a4e7b30012b6437c', _originalId: '5a977492a4e7b30012b6437a', name: '需求', @@ -122,7 +120,7 @@ export const taskScenarioFieldConfig: TaskScenarioFieldConfigSchema = { ] } -export const eventScenarioFieldConfig: EventScenarioFieldConfigSchema = { +export const eventScenarioFieldConfig = { _id: '59fa8b97d564c422688da661', _originalId: '59fa8b97d564c422688da660', name: '日程', @@ -165,13 +163,13 @@ export const eventScenarioFieldConfig: EventScenarioFieldConfigSchema = { displayed: false } -export const orgTaskScenarioFieldConfig: TaskScenarioFieldConfigSchema = { +export const orgTaskScenarioFieldConfig = { ...taskScenarioFieldConfig, boundToObjectType: 'organization', _boundToObjectId: 'mock-organization-id' } -export const orgEventScenarioFieldConfig: EventScenarioFieldConfigSchema = { +export const orgEventScenarioFieldConfig = { ...eventScenarioFieldConfig, boundToObjectType: 'organization', _boundToObjectId: 'mock-organization-id' diff --git a/test/net/asyncLoadRDB.ts b/test/net/asyncLoadRDB.ts index 7ac150bc2..90ca2607d 100644 --- a/test/net/asyncLoadRDB.ts +++ b/test/net/asyncLoadRDB.ts @@ -9,6 +9,7 @@ import { LikeSchema, SocketMock } from '../index' +import { PostId, TaskId, UserId } from 'teambition-types' import { projectPosts } from '../fixtures/posts.fixture' import like from '../fixtures/like.fixture' import userMe from '../fixtures/user.fixture' @@ -23,7 +24,7 @@ describe('Async load reactivedb Spec', () => { let mockResponse: (m: T, delay?: number | Promise) => void let socket: SocketMock - const userId = myFixture.myRecent[0]['_executorId'] + const userId = myFixture.myRecent[0]['_executorId'] as UserId beforeEach(() => { sdk = createSdkWithoutRDB() @@ -43,7 +44,7 @@ describe('Async load reactivedb Spec', () => { const [fixture] = projectPosts mockResponse(fixture) - yield sdk.getPost(fixture._id) + yield sdk.getPost(fixture._id as PostId) .values() .do(([r]) => { expect(r).to.deep.equal(fixture) @@ -53,7 +54,7 @@ describe('Async load reactivedb Spec', () => { it('getLike should response correct data without reactivedb', done => { mockResponse(like) - sdk.getLike('task', 'mocktask') + sdk.getLike('task', 'mocktask' as TaskId) .values() .subscribe(([r]) => { delete r._id @@ -75,7 +76,7 @@ describe('Async load reactivedb Spec', () => { it('getTask should response correct data without reactivedb', function* () { const fixture = task mockResponse(fixture) - yield sdk.getTask(fixture._id) + yield sdk.getTask(fixture._id as TaskId) .values() .do(([r]) => { expect(r).to.deep.equal(fixture) @@ -128,7 +129,7 @@ describe('Async load reactivedb Spec', () => { const [fixture] = projectPosts mockResponse(fixture) - yield sdk.getPost(fixture._id) + yield sdk.getPost(fixture._id as PostId) .values() yield loadRDB(sdk) @@ -145,10 +146,10 @@ describe('Async load reactivedb Spec', () => { ...like, isLike: false, _id: 'mocktask:like' }) - yield sdk.getLike('task', 'mocktask') + yield sdk.getLike('task', 'mocktask' as TaskId) .values() - yield sdk.toggleLike('task', 'mocktask', true) + yield sdk.toggleLike('task', 'mocktask' as TaskId, true) yield loadRDB(sdk) @@ -167,7 +168,7 @@ describe('Async load reactivedb Spec', () => { mockResponse(fixture) - yield sdk.getPost(fixture._id) + yield sdk.getPost(fixture._id as PostId) .values() yield socket.emit('destroy', 'post', fixture._id) @@ -185,7 +186,7 @@ describe('Async load reactivedb Spec', () => { const [fixture] = projectPosts mockResponse(fixture) - yield sdk.getPost(fixture._id) + yield sdk.getPost(fixture._id as PostId) .values() yield socket.emit('change', 'post', fixture._id, {