Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

fixed issues related to projects

Blue Mouse32c853774a08
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index bd084a101..c040a0a82 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -9,7 +9,6 @@ import * as _keys from 'lodash/keys'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
import { hash } from 'blake3'
-import { promises as fs } from 'fs'
import {
Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,
} from '@nestjs/common'
@@ -20,6 +19,7 @@ import {
UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisUserCountKey,
redisProjectCountCacheTimeout, isSelfhosted, // REDIS_SESSION_SALT_KEY,
} from '../common/constants'
+import { getJSONProjects } from '../common/utils'
import { PageviewsDTO } from './dto/pageviews.dto'
import { EventsDTO } from './dto/events.dto'
import { ProjectService } from '../project/project.service'
@@ -42,14 +42,7 @@ export class AnalyticsService {
if (_isEmpty(project)) {
if (isSelfhosted) {
- let projects
-
- try {
- const rawData = await fs.readFile('../../projects.json', 'utf8')
- projects = JSON.parse(rawData)
- } catch (e) {
- throw new InternalServerErrorException('Error while reading projects data')
- }
+ const projects = await getJSONProjects()
project = projects[pid]
} else {
project = await this.projectService.findOne(pid, {
@@ -89,14 +82,7 @@ export class AnalyticsService {
let pids
if (isSelfhosted) {
- let projects
-
- try {
- const rawData = await fs.readFile('../../projects.json', 'utf8')
- projects = JSON.parse(rawData)
- } catch (e) {
- throw new InternalServerErrorException('Error while reading projects data')
- }
+ const projects = await getJSONProjects()
pids = _keys(projects)
} else {
pids = await this.projectService.find({
diff --git a/src/common/constants.ts b/src/common/constants.ts
index a1962dbc0..e245be1b2 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -88,7 +88,7 @@ const initialiseClickhouse = async () => {
const initialiseSelfhosted = () => {
if (isSelfhosted) {
- fs.writeFile('../../projects.json', '{}', { flag: 'wx' }, () => {})
+ fs.writeFile('../projects.json', '{}', { flag: 'wx' }, () => {})
}
}
diff --git a/src/common/utils.ts b/src/common/utils.ts
index b72236d5e..9ab3261f9 100644
--- a/src/common/utils.ts
+++ b/src/common/utils.ts
@@ -1,6 +1,7 @@
-import * as _sample from 'lodash/sample'
-import { ForbiddenException } from '@nestjs/common'
+import { ForbiddenException, InternalServerErrorException } from '@nestjs/common'
import { hash } from 'blake3'
+import { promises as fs } from 'fs'
+import * as _sample from 'lodash/sample'
import * as _toNumber from 'lodash/toNumber'
import { redis } from './constants'
@@ -47,6 +48,23 @@ const checkRateLimit = async (ip: string, action: string, reqAmount = RATE_LIMIT
await redis.set(rlHash, 1 + rlCount, 'EX', reqTimeout)
}
+const getJSONProjects = async () => {
+ try {
+ const rawData = await fs.readFile('../projects.json', 'utf8')
+ return JSON.parse(rawData)
+ } catch (e) {
+ throw new InternalServerErrorException('Error while reading projects data')
+ }
+}
+
+const setJSONProjects = async (projects) => {
+ try {
+ await fs.writeFile('../projects.json', JSON.stringify(projects))
+ } catch (e) {
+ throw new InternalServerErrorException('Error while saving projects data')
+ }
+}
+
export {
- getRandomTip, checkRateLimit,
+ getRandomTip, checkRateLimit, getJSONProjects, setJSONProjects,
}
diff --git a/src/project/project.controller.ts b/src/project/project.controller.ts
index af7646772..64e6ca6ad 100644
--- a/src/project/project.controller.ts
+++ b/src/project/project.controller.ts
@@ -3,11 +3,11 @@ import {
BadRequestException, HttpCode, NotFoundException, ForbiddenException, InternalServerErrorException,
} from '@nestjs/common'
import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'
-import { promises as fs } from 'fs'
import * as _isEmpty from 'lodash/isEmpty'
import * as _map from 'lodash/map'
import * as _trim from 'lodash/trim'
import * as _size from 'lodash/size'
+import * as _values from 'lodash/values'
import { ProjectService } from './project.service'
import { UserType, ACCOUNT_PLANS } from '../user/entities/user.entity'
@@ -22,6 +22,7 @@ import { AppLoggerService } from '../logger/logger.service'
import {
redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout, clickhouse, isSelfhosted,
} from '../common/constants'
+import { getJSONProjects, setJSONProjects } from '../common/utils'
@ApiTags('Project')
@Controller('project')
@@ -39,12 +40,22 @@ export class ProjectController {
@ApiResponse({ status: 200, type: [Project] })
@UseGuards(RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
- async get(@CurrentUserId() userId: string, @Query('take') take: number | undefined, @Query('skip') skip: number | undefined): Promise<Pagination<Project> | Project[]> {
+ async get(@CurrentUserId() userId: string, @Query('take') take: number | undefined, @Query('skip') skip: number | undefined): Promise<Pagination<Project> | Project[] | object> {
this.logger.log({ userId, take, skip }, 'GET /project')
- const where = Object()
- where.admin = userId
+ if (isSelfhosted) {
+ const projects = await getJSONProjects()
+ const results = _values(projects)
+ return {
+ results,
+ page_total: _size(results),
+ total: _size(results),
+ }
+ } else {
+ const where = Object()
+ where.admin = userId
- return await this.projectService.paginate({ take, skip }, where)
+ return await this.projectService.paginate({ take, skip }, where)
+ }
}
@Get('/:id')
@@ -54,7 +65,14 @@ export class ProjectController {
async getOne(@Param('id') id: string): Promise<Project> {
this.logger.log({ id }, 'GET /project/:id')
if (!isValidPID(id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
- const project = await this.projectService.findOne(id)
+ let project
+
+ if (isSelfhosted) {
+ const projects = await getJSONProjects()
+ project = projects[id]
+ } else {
+ await this.projectService.findOne(id)
+ }
if (_isEmpty(project)) throw new NotFoundException('Project was not found in the database')
return project
@@ -68,14 +86,7 @@ export class ProjectController {
this.logger.log({ projectDTO, userId }, 'POST /project')
if (isSelfhosted) {
- let projects
-
- try {
- const rawData = await fs.readFile('../../projects.json', 'utf8')
- projects = JSON.parse(rawData)
- } catch (e) {
- throw new InternalServerErrorException('Error while reading projects data')
- }
+ const projects = await getJSONProjects()
this.projectService.validateProject(projectDTO)
this.projectService.checkIfIDUniqueJSON(projects, projectDTO.id)
@@ -83,13 +94,10 @@ export class ProjectController {
const project = new Project()
Object.assign(project, projectDTO)
project.origins = _map(projectDTO.origins, _trim)
+ project.active = true
projects[project.id] = project
- try {
- await fs.writeFile('../../projects.json', JSON.stringify(projects))
- } catch (e) {
- throw new InternalServerErrorException('Error while saving project')
- }
+ await setJSONProjects(projects)
return project
} else {
@@ -142,14 +150,7 @@ export class ProjectController {
let project
if (isSelfhosted) {
- let projects
-
- try {
- const rawData = await fs.readFile('../../projects.json', 'utf8')
- projects = JSON.parse(rawData)
- } catch (e) {
- throw new InternalServerErrorException('Error while reading projects data')
- }
+ const projects = await getJSONProjects()
project = projects[id]
if (_isEmpty(project)) {
@@ -160,11 +161,7 @@ export class ProjectController {
project.name = projectDTO.name
projects[project.id] = project
- try {
- await fs.writeFile('../../projects.json', JSON.stringify(projects))
- } catch (e) {
- throw new InternalServerErrorException('Error while saving project')
- }
+ await setJSONProjects(projects)
} else {
project = await this.projectService.findOneWithRelations(id)
@@ -201,25 +198,13 @@ export class ProjectController {
if (!isValidPID(id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
if (isSelfhosted) {
- let projects
-
- try {
- const rawData = await fs.readFile('../../projects.json', 'utf8')
- projects = JSON.parse(rawData)
- } catch (e) {
- throw new InternalServerErrorException('Error while reading projects data')
- }
-
+ const projects = await getJSONProjects()
const project = projects[id]
if (_isEmpty(project)) {
throw new NotFoundException(`Project with ID ${id} does not exist`)
}
delete projects[id]
- try {
- await fs.writeFile('../../projects.json', JSON.stringify(projects))
- } catch (e) {
- throw new InternalServerErrorException('Error while saving project')
- }
+ await setJSONProjects(projects)
const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`
const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`