Skip to content

Commit

Permalink
Merge pull request #154 from TogetherCrew/153-update-community-schema…
Browse files Browse the repository at this point in the history
…-to-support-role-based-permissions-in-upv1

153 update community schema to support role based permissions in upv1
  • Loading branch information
cyri113 authored Mar 14, 2024
2 parents f03497a + e070968 commit 649b0ee
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 85 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ COPY . .
RUN npm ci

FROM base AS test
CMD [ "npx", "jest", "--coverage" ]
CMD [ "npx", "jest", "--runInBand", "--coverage" ]

FROM base AS build
RUN npm run build

FROM build AS prod
RUN npm ci --omit=dev
CMD ["npm", "run", "start"]
CMD ["npm", "run", "start"]
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Community {
users?: [Types.ObjectId],
platforms?: [Types.ObjectId],
tcaAt?: Date;
roles?: ICommunityRoles[];
}
```

Expand Down
41 changes: 18 additions & 23 deletions __tests__/unit/models/community.mode.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Community, User, Platform } from '../../../src/models';
import { ICommunity } from '../../../src/interfaces';
import { Types } from 'mongoose';
// import setupTestDB from '../../utils/setupTestDB';
import setupTestDB from '../../utils/setupTestDB';

// setupTestDB();
setupTestDB();

describe('Community model', () => {
describe('Community validation', () => {
Expand All @@ -20,31 +20,26 @@ describe('Community model', () => {
test('should correctly validate a valid community', async () => {
await expect(new Community(community).validate()).resolves.toBeUndefined();
});
describe('Middlewares', () => {
test('Pre Remove: should clean up when community is deleted', async () => {
const user = new User({ discordId: 'discordId' });
await user.save();

// describe('Cascade deletes', () => {
const community = new Community({ users: [user._id], name: 'community' });
await community.save();
user.communities?.push(community._id);

// test('should clean up when community is deleted', async () => {
// const user = new User({ discordId: 'discordId' });
// await user.save();
const platform = new Platform({ name: 'platform', community: community._id });
await platform.save();

// const community = new Community({ users: [user._id], name: 'community' });
// await community.save();
// user.communities?.push(community._id)
await community.remove();

// const platform = new Platform({ name: 'platform', community: community._id });
// await platform.save();
const userDoc = await User.findById(user._id);
expect(userDoc?.communities).not.toContain(community._id);

// community.platforms?.push(platform._id);
// await community.save();

// await community.remove();

// const userDoc = await User.findById(user._id);
// expect(userDoc?.communities).not.toContain(community._id);

// const platformDoc = await Platform.findById(platform._id);
// expect(platformDoc).toBe(null);
// });
// });
const platformDoc = await Platform.findById(platform._id);
expect(platformDoc).toBe(null);
});
});
});
});
69 changes: 50 additions & 19 deletions __tests__/unit/models/platform.model.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Platform, Community } from '../../../src/models';
import { Platform, Community, User } from '../../../src/models';
import { IPlatform } from '../../../src/interfaces';
import { Types } from 'mongoose';
// import setupTestDB from '../../utils/setupTestDB';
import setupTestDB from '../../utils/setupTestDB';

// setupTestDB();
setupTestDB();

describe('Platform model', () => {
describe('Platform validation', () => {
Expand All @@ -24,27 +24,58 @@ describe('Platform model', () => {
await expect(new Platform(platform).validate()).resolves.toBeUndefined();
});

// describe('Cascade deletes', () => {
describe('Middlewares', () => {
test('Pre Remove: should clean up when platform is deleted', async () => {
const user = new User({ discordId: 'discordId' });
await user.save();

// test('should clean up when community is deleted', async () => {
// const community = new Community({ users: [new Types.ObjectId()], name: 'community' });
// await community.save();
const community = new Community({ users: [user._id], name: 'community' });
await community.save();

// const platform = new Platform({ name: 'platform', community: community._id });
// await platform.save();
const platform = new Platform({ name: 'platform', community: community._id });
await platform.save();
let communityDoc = await Community.findById(community.id);
if (communityDoc?.platforms) {
const idAsString = platform.id.toHexString ? platform.id.toHexString() : platform.id;
expect(communityDoc.platforms[0].toHexString()).toBe(idAsString);
}
await platform.remove();
communityDoc = await Community.findById(community.id);
expect(communityDoc?.platforms).toEqual([]);
expect(communityDoc?.roles).toEqual([]);

// community.platforms?.push(platform._id);
// await community.save();
const platformDoc = await Platform.findById(platform._id);
expect(platformDoc).toBe(null);
});

// await platform.remove();
test('Post Save: should add platformId to the community and admin role for the creator of community', async () => {
const user = new User({ discordId: 'discordId' });
await user.save();

// const communityDoc = await Community.findById(community._id);
const community = new Community({ users: [user._id], name: 'community' });
await community.save();
user.communities?.push(community._id);

// expect(communityDoc?.platforms).not.toContain(platform._id);

// const platformDoc = await Platform.findById(platform._id);
// expect(platformDoc).toBe(null);
// });
// });
const platform = new Platform({ name: 'platform', community: community._id });
await platform.save();
const communityDoc = await Community.findById(community.id);
if (communityDoc?.platforms && communityDoc?.roles) {
const idAsString = platform.id.toHexString ? platform.id.toHexString() : platform.id;
expect(communityDoc.platforms[0].toHexString()).toBe(idAsString);
expect(JSON.parse(JSON.stringify(communityDoc.roles))).toEqual([
{
_id: expect.anything(),
roleType: 'admin',
source: {
platform: 'discord',
identifierType: 'member',
identifierValues: [user.discordId],
platformId: platform._id.toHexString(),
},
},
]);
}
});
});
});
});
28 changes: 13 additions & 15 deletions __tests__/unit/models/user.model.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { User, Community } from '../../../src/models';
import { IUser } from '../../../src/interfaces';
import { Types } from 'mongoose';
// import setupTestDB from '../../utils/setupTestDB';
import setupTestDB from '../../utils/setupTestDB';

// setupTestDB();
setupTestDB();

describe('User model', () => {
describe('User validation', () => {
Expand All @@ -22,20 +22,18 @@ describe('User model', () => {
});
});

// describe('Cascade deletes', () => {
describe('Middlewares', () => {
test('Pre Remove: should remove user reference from community when user is deleted', async () => {
const user = new User({ discordId: 'discordId' });
await user.save();

// test('should remove user reference from community when user is deleted', async () => {
// const user = new User({ discordId: 'discordId' });
// await user.save();
const community = new Community({ users: [user._id], name: 'community' });
await community.save();

// const community = new Community({ users: [user._id], name: 'community' });
// await community.save();
await user.remove();

// await user.remove();

// const communityDoc = await Community.findById(community._id);
// expect(communityDoc?.users).not.toContain(user._id);

// });
// });
const communityDoc = await Community.findById(community._id);
expect(communityDoc?.users).not.toContain(user._id);
});
});
});
34 changes: 17 additions & 17 deletions __tests__/utils/setupTestDB.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
// import mongoose from 'mongoose';
// import config from '../../src/config';
import mongoose from 'mongoose';
import config from '../../src/config';

// const setupTestDB = () => {
// beforeAll(async () => {
// mongoose.set('strictQuery', false);
// await mongoose.connect(config.mongoose.serverURL);
// });
const setupTestDB = () => {
beforeAll(async () => {
mongoose.set('strictQuery', false);
await mongoose.connect(config.mongoose.serverURL);
});

// beforeEach(async () => {
// await Promise.all(
// Object.values(mongoose.connection.collections).map(async (collection) => collection.deleteMany({})),
// );
// });
beforeEach(async () => {
await Promise.all(
Object.values(mongoose.connection.collections).map(async (collection) => collection.deleteMany({})),
);
});

// afterAll(async () => {
// await mongoose.disconnect();
// });
// };
afterAll(async () => {
await mongoose.disconnect();
});
};

// export default setupTestDB;
export default setupTestDB;
26 changes: 24 additions & 2 deletions docker-compose.test.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
---
version: '3.9'
version: "3.9"

services:
app:
build:
context: .
target: test
dockerfile: Dockerfile
environment:
- DB_HOST=mongo
- DB_PORT=27017
- DB_USER=root
- DB_PASSWORD=pass
- DB_NAME=RnDAO
volumes:
- ./coverage:/project/coverage
depends_on:
mongo:
condition: service_healthy
mongo:
image: "mongo:5.0.10"
environment:
- MONGO_INITDB_DATABASE=RnDAO
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=pass
healthcheck:
test: echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
interval: 60s
timeout: 10s
retries: 2
start_period: 40s


4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "@togethercrew.dev/db",
"version": "3.0.32",
"version": "3.0.33",
"description": "All interactions with DB",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"start": "node ./dist/index.js",
"dev": "nodemon ./src/index.ts",
"test": "jest --detectOpenHandles",
"test": "env-cmd -f ./src/config/test.env jest --runInBand --detectOpenHandles",
"format": "prettier --write \"src/**/*.ts\" \"__tests__/**/*.ts\" \"*.ts\" ",
"prepublishOnly": "npm test",
"version": "npm run format && git add -A src",
Expand Down
6 changes: 3 additions & 3 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ if (error != null) {

export default {
mongoose: {
serverURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}/${envVars.DB_NAME}`,
botURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}`,
dbURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}`,
serverURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}/${envVars.DB_NAME}?authSource=admin`,
botURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}?authSource=admin`,
dbURL: `mongodb://${envVars.DB_USER}:${envVars.DB_PASSWORD}@${envVars.DB_HOST}:${envVars.DB_PORT}?authSource=admin`,
},
};
11 changes: 11 additions & 0 deletions src/interfaces/Community.interface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { type Model, type Types } from 'mongoose';

export interface ICommunityRoles {
roleType: 'view' | 'admin';
source: {
platform: 'discord';
identifierType: 'member' | 'role';
identifierValues: string[];
platformId: Types.ObjectId;
};
}
export interface ICommunity {
name: string;
avatarURL?: string;
users: Types.ObjectId[];
platforms?: Types.ObjectId[];
tcaAt?: Date;
roles?: ICommunityRoles[];
}

export interface ICommunityUpdateBody {
Expand All @@ -14,6 +24,7 @@ export interface ICommunityUpdateBody {
users?: Types.ObjectId[];
platforms?: Types.ObjectId[];
tcaAt?: Date;
roles?: ICommunityRoles[];
}

export interface CommunityModel extends Model<ICommunity> {
Expand Down
33 changes: 32 additions & 1 deletion src/models/schemas/Community.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,39 @@ const communitySchema = new Schema<ICommunity, CommunityModel>(
tcaAt: {
type: Date,
},
roles: [
{
roleType: {
type: String,
enum: ['view', 'admin'],
required: true,
},
source: {
platform: {
type: String,
enum: ['discord'],
required: true,
},
identifierType: {
type: String,
enum: ['member', 'role'],
required: true,
},
identifierValues: [
{
type: String,
required: true,
},
],
platformId: {
type: Schema.Types.ObjectId,
ref: 'Platform',
required: true,
},
},
},
],
},

{ timestamps: true },
);

Expand Down
Loading

0 comments on commit 649b0ee

Please sign in to comment.