Module:RemoteData

From Buddha-Nature
Revision as of 04:11, 25 July 2025 by JeremiP (talk | contribs) ((by SublimeText.Mediawiker))

Documentation for this module may be created at Module:RemoteData/doc

local p = {}

function p.get(frame)

		local args = frame.args
		local pargs = frame:getParent().args
		local prop = ''
		if args.prop then
			prop = args.prop
		else
			prop = pargs[1]
		end
		local source = args.source

		local remoteData = mw.smw.ask( '[[' .. mw.title.getCurrentTitle().subpageText .. ']]|?' .. prop .. '#|mainlabel=-|source=' .. source )

		if remoteData then
			for _, data in pairs( remoteData ) do
				for property, value in pairs( data ) do
					return frame:preprocess( value )
				end
			end
		else
			return 'No data! ¯\\_(ツ)_/¯'
		end
end

function p.set(frame)

    local pargs = frame:getParent().args

    local properties = ''
    for value in string.gmatch(pargs.props, "([^;]+)") do
        properties = properties .. "|?" .. value .. "#"
    end

    local extQuery = mw.uri.encode( "[[" .. mw.title.getCurrentTitle().subpageText .. "]]" .. properties .. "|limit=10000|valuesep=;|sep=;" )

    -- local testQuery = "https://" .. pargs.source .. ".tsadra.org/api.php?action=ask&query=" .. extQuery .. "&format=json&api_version=3"
    -- if testQuery then
    --     return testQuery
    -- end

    local remoteContent, rcErrors = mw.ext.externalData.getExternalData("https://" .. pargs.source .. ".tsadra.org/api.php?action=ask&query=" .. extQuery .. "&format=json&api_version=3")
    local json = not rcErrors and remoteContent.__json or false

    if rcErrors then
        return rcErrors
    end
    -- EXAMPLE: https://research.tsadra.org/api.php?action=ask&query=%5B%5BRhoton%2C+J.%5D%5D%7C%3FFirstImage%7C%3FMainNamePhon%7Climit%3D10000&format=json&api_version=3

    local dataStore = {}

    if #json then
        for _, result in ipairs(json.query.results) do
            for name, values in pairs (result) do
                for prop, value in pairs (values.printouts) do
                    local dataOutput = value
                    if type( value ) == 'table' then
                        dataOutput = mw.text.listToText( value, '; ')
                    end
                    table.insert(dataStore, prop .. '=' .. dataOutput)
                    if pargs.sep then
                        table.insert(dataStore, '+sep=' .. pargs.sep)
                    end
                end
            end
        end
    end

    local dataStored = mw.smw.set( dataStore )

    if dataStored == true then
        return ''
    else
        return 'An error occurred during the storage process. Message reads ' .. dataStored.error
    end

end

return p