Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documents from dapi #308

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 78 additions & 8 deletions packages/api/src/DAPI.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,98 @@
const { Identifier } = require('dash').PlatformProtocol
const {Identifier} = require('dash').PlatformProtocol

class DAPI {
dapi
dpp

constructor (dapi, dpp) {
constructor(dapi, dpp) {
this.dapi = dapi
this.dpp = dpp
}

async getIdentityBalance (identifier) {
const { balance } = await this.dapi.platform.getIdentityBalance(Identifier.from(identifier))
async getIdentityBalance(identifier) {
const {balance} = await this.dapi.platform.getIdentityBalance(Identifier.from(identifier))
return balance
}

async getTotalCredits () {
const { totalCreditsInPlatform } = await this.dapi.platform.getTotalCreditsInPlatform()
async getTotalCredits() {
const {totalCreditsInPlatform} = await this.dapi.platform.getTotalCreditsInPlatform()
return totalCreditsInPlatform
}

async getEpochsInfo (count, start, ascending) {
const { epochsInfo } = await this.dapi.platform.getEpochsInfo(start, count, { ascending })
async getEpochsInfo(count, start, ascending) {
const {epochsInfo} = await this.dapi.platform.getEpochsInfo(start, count, {ascending})
return epochsInfo
}

async getDocuments(type, documentSchemas, dataContractData, identifier, page, limit) {
const dataContract = await this.dpp.dataContract.createFromObject(dataContractObject)

const documentObject = {
$format_version: "0",
documentSchemas,
version: dataContractData.version,
ownerId: dataContractData.owner,
id: identifier
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
let startAfter

let options = {
limit: page * limit > 100 ? 100 : limit,
}

if(page*limit>limit){
const cycles = Math.ceil((limit * page) / (page * limit > 100 ? 100 : limit))

for (let i = 0; i < cycles - 1; i++) {
if (startAfter) {
options.startAfter = startAfter
}

const docs = await this.dapi.getDocuments(
type,
documentObject,
options
)

if (docs.length === (page * limit > 100 ? 100 : limit)) {
startAfter = docs[docs.length - 1].getId()
} else {
return response.status(400).send({message: `out of range`})
}
}

options.limit = limit
const docs = await this.dapi.getDocuments(
type,
documentObject,
options
)

if (docs.length === limit) {
startAfter = docs[docs.length - 1].getId()
} else {
return response.status(400).send({message: `out of range`})
}
}

options = {
orderBy: orderData.map(el => typeof el === 'string' ? JSON.parse(el) : el),
limit: limit,
}

if (startAfter) {
options.startAfter = startAfter
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


const data = await this.dapi.platform.getDocuments(Identifier.from(dataContractObject.id), type, options)

return data.documents.map((document) =>
this.dpp.document.createExtendedDocumentFromDocumentBuffer(document, type, dataContract))
}
}

module.exports = DAPI
45 changes: 40 additions & 5 deletions packages/api/src/controllers/DocumentsController.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,65 @@
const DocumentsDAO = require('../dao/DocumentsDAO')
const DataContractsDAO = require('../dao/DataContractsDAO')

class DocumentsController {
constructor (knex) {
constructor(knex, dapi) {
this.documentsDAO = new DocumentsDAO(knex)
this.dataContractsDAO = new DataContractsDAO(knex)
this.dapi = dapi
}

getDocumentByIdentifier = async (request, response) => {
const { identifier } = request.params
const {identifier} = request.params

const document = await this.documentsDAO.getDocumentByIdentifier(identifier)

if (!document) {
response.status(404).send({ message: 'not found' })
return response.status(404).send({message: 'not found'})
}

response.send(document)
}

getDocumentsByDataContract = async (request, response) => {
const { identifier } = request.params
const { page = 1, limit = 10, order = 'asc' } = request.query
const {identifier} = request.params
const {page = 1, limit = 10, order = 'asc'} = request.query

const documents = await this.documentsDAO.getDocumentsByDataContract(identifier, Number(page ?? 1), Number(limit ?? 10), order)

response.send(documents)
}

getDocumentsWithTypeByDataContract = async (request, response) => {
const {identifier, type} = request.params
const {page = 1, limit = 10, orderData = []} = request.query

const dataContractData = await this.dataContractsDAO.getDataContractByIdentifier(identifier)

if (!dataContractData?.schema) {
return response.status(404).send({message: 'not found'})
}

const documentsCount = await this.documentsDAO.getDocumentsCountByDataContract(identifier)

if (documentsCount !== 0 && limit * page > documentsCount) {
return response.status(400).send({message: `out of range (${documentsCount})`})
}

const documentSchemas = JSON.parse(dataContractData.schema)
const documentTypes = Object.keys(documentSchemas)

if (!documentTypes.includes(type)) {
return response.status(400).send({message: `type not found (${documentTypes.join(', ')})`})
}

const documents = await this.dapi.getDocuments(
type,
documentObject,
options
)

response.send(documents)
}
}

module.exports = DocumentsController
11 changes: 10 additions & 1 deletion packages/api/src/dao/DocumentsDAO.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const Document = require('../models/Document')
const PaginatedResultSet = require('../models/PaginatedResultSet')

module.exports = class DocumentsDAO {
constructor (knex) {
constructor(knex) {
this.knex = knex
}

Expand Down Expand Up @@ -77,4 +77,13 @@ module.exports = class DocumentsDAO {

return new PaginatedResultSet(resultSet, page, limit, totalCount)
}

getDocumentsCountByDataContract = async (identifier) => {
const [{count}] = await this.knex('documents')
.count('*')
.leftJoin('data_contracts', 'data_contracts.id', 'documents.data_contract_id')
.where('data_contracts.identifier', identifier)

return Number(count ?? 0)
}
}
15 changes: 15 additions & 0 deletions packages/api/src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ module.exports = ({
querystring: { $ref: 'paginationOptions#' }
}
},
{
path: '/dataContract/:identifier/documents/:type',
method: 'GET',
handler: documentsController.getDocumentsWithTypeByDataContract,
schema: {
params: {
type: 'object',
properties: {
identifier: { $ref: 'identifier#' },
type: { type: 'string' },
}
},
querystring: { $ref: 'paginationOptions#' }
}
},
{
path: '/document/:identifier',
method: 'GET',
Expand Down
3 changes: 3 additions & 0 deletions packages/api/src/schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ const schemaTypes = [
type: ['string', 'null'],
enum: ['asc', 'desc']
},
orderData: {
type: ['array', 'null'],
},
orderBy: {
type: ['string', 'null'],
enum: ['block_height', 'documents_count', 'tx_count', 'balance']
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ module.exports = {
const blocksController = new BlocksController(knex)
const transactionsController = new TransactionsController(client, knex)
const dataContractsController = new DataContractsController(knex)
const documentsController = new DocumentsController(knex)
const documentsController = new DocumentsController(knex, dapi)
const identitiesController = new IdentitiesController(knex, dapi)
const validatorsController = new ValidatorsController(knex, dapi)
const rateController = new RateController()
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const crypto = require('crypto')
const StateTransitionEnum = require('./enums/StateTransitionEnum')
const net = require('net')
const { TCP_CONNECT_TIMEOUT } = require('./constants')
const {TCP_CONNECT_TIMEOUT} = require('./constants')

const getKnex = () => {
return require('knex')({
Expand All @@ -12,7 +12,7 @@ const getKnex = () => {
user: process.env.POSTGRES_USER,
database: process.env.POSTGRES_DB,
password: process.env.POSTGRES_PASS,
ssl: process.env.POSTGRES_SSL ? { rejectUnauthorized: false } : false
ssl: process.env.POSTGRES_SSL ? {rejectUnauthorized: false} : false
}
})
}
Expand Down Expand Up @@ -174,4 +174,4 @@ const calculateInterval = (start, end) => {
}, intervalsInRFC[0])
}

module.exports = { hash, decodeStateTransition, getKnex, checkTcpConnect, calculateInterval }
module.exports = {hash, decodeStateTransition, getKnex, checkTcpConnect, calculateInterval}
Loading